Reputation: 1363
My schema looks like
point: { type: Number, default: 0 },
effort: { type: Number, default: 0 },
note: { type: String },
dateRated: {type: Date},
createDate: {type:Date},
dateInfoId: {type: String}
I'm trying to calculate average of point and effort by passing certain _id
's
My code looks like
frequencies = ["mongo object id"];
Frequency.aggregate([{
$project: {
_id: {
$in: ['$_id', frequencies]
},
point: {
$ne: ['$point', 0]
}
}
}, {
$group: {
_id: {
$in: ['$_id', frequencies]
},
average: {
$avg: "$point"
},
effort: {
$avg: "$effort"
}
}
}], (err, result) => {});
But it always returns [ { _id: false, average: null, effort: null } ]
. What should I do to calculate the average of my points and effort?
Upvotes: 2
Views: 858
Reputation: 17915
It has to be like this :
Frequency.aggregate([{
$match: {
_id: {
$in: frequencies
}, point: { $ne: 0 }
}
}, {
$group: {
_id: null,
average: {
$avg: "$point"
},
effort: {
$avg: "$effort"
}
}
}])
Here $match
would retain only the documents that match with passed frequencies
and where point != 0
, then after all you need is to iterate through all documents to get the average of required two fields, So $group
helps to do that, where _id: null
or _id: ''
will iterate through all of the leftover documents, you no need to specify a filter again in group stage.
Upvotes: 1