Reputation: 71
I want my average which is found in the MongoDB aggregation to come up with a roundup value
[
{
"_id": "581c3d9c55421c16ecaf0b26",
"uDept": "CoE Design & Research",
"uName": "Saurabh Raman",
"rateVal": 3,
"timeStamp": "11/4/2016 13:17",
"__v": 0
},
{
"_id": "581c437ea3d9f6087ce3b21e",
"uDept": "CoE Design & Research",
"uName": "Sachin P Singh",
"rateVal": 4,
"timeStamp": "11/4/2016 13:42",
"__v": 0
},
{
"_id": "581c6d74a3d9f6087ce3b21f",
"uDept": "Training",
"uName": "Rahul Shakya",
"rateVal": 4,
"timeStamp": "11/4/2016 16:35",
"__v": 0
}
]
The query which I run to obtain the average of "rateVal"
db.calcR.aggregate([
{
$group: {
_id: null,
avg: {$avg: '$rateVal'},
}
}
The output is { avg: 3.6666 }
but ideally I want it to appear as 4
[
{
"_id": null,
"avg": 3.6666666666666665,
}
]
Upvotes: 5
Views: 5328
Reputation: 41
Since by documentation unary operator accumulators(eg: $round) are not allowed at $group stage, you can use them at $addFields stage. This way, in your case, the avg field defined at group stage will be overwritten by $addFields stage:
$addFields: {
avg: { $round: ['$avg', -1] },
},
Upvotes: 4