1
我想用mongodb中的$ avg来计算字段的平均值。 代码: -
DoctorsReview.aggregate([
{
$match: {
doctor: doctorsId
}
},
{
$group: {
_id: null,
averageRating: { $avg: "$rating" },
count: { $sum: 1 }
}
}],function(error, result){
if(error)
console.log(error);
console.log(result);
});
的问题是,当我打了第一次查询,它返回一个空数组,但是当我再次打它,它返回我预计在以前的命中结果。
仅供参考我试图计算在DoctorsReview模型中对应于doctorsId的评级的平均值。
请帮忙。
DoctorsReview样本: -
{
"_id" : ObjectId("56b473b0b9d8b5b01c6d1529"),
"rating" : NumberInt(4),
"review" : "Poor",
"user" : ObjectId("5673a0e86a8141c00c85a743"),
"doctor" : ObjectId("56b1cbb4e8e806f8229c1afa"),
"date" : ISODate("2010-12-12T00:00:00.000+0000"),
"time" : NumberInt(19),
"__v" : NumberInt(0)
}
预期的响应: -
[{ _id: null, averageRating: 4, count: 1}];
所以当我打的第一次,我得到空数组作为回应,但是当服务器再次袭来,我得到了预期的回应。