I'm trying to round the average salary to 2 decimal places. I'm stumped, I can get either everyones salary to 2 decimal places
db.employees.aggregate([{$project: {_id: null, 'roundedSal':{$round: [{$avg: '$salary'}]}}}])
which returns
{ "_id": null, "roundedSal": 48501.24 } { "_id": null, "roundedSal": 45999.71 } { "_id": null, "roundedSal": 35554.54 } { "_id": null, "roundedSal": 47700 } { "_id": null, "roundedSal": 48123.25 } { "_id": null, "roundedSal": 44415.94 } { "_id": null, "roundedSal": 42925.26 } { "_id": null, "roundedSal": 31500.66 } { "_id": null, "roundedSal": 50500.25 }
or get the overall average
db.employees.aggregate([{$group: {_id: null, 'roundedSal':{$avg: '$salary'}}}])
{ "_id" : null, "roundedSal" : 43913.427777777775 }
but I can't manage to figure out how to round this to two decimal places without an error being thrown
Please read the mongo documentation it's one of the bestest documentantions in my opinion.
// { $round : [ <number>, <place> ] }
db.employees.aggregate([{$project: {_id: null, 'roundedSal':{$round: [{$avg: '$salary'}, 2]}}}])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.