【问题标题】:$Avg aggregation in mongomongo 中的 $Avg 聚合
【发布时间】:2016-02-05 19:47:29
【问题描述】:

我正在尝试在 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 模型中的医生 ID 对应的平均评分。

请帮忙。

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}];

所以当我第一次点击时,我得到空数组作为响应,但是当再次点击服务器时,我得到了预期的响应。

【问题讨论】:

    标签: node.js mongodb


    【解决方案1】:

    下面试试,我没试过。

    { 
            $match: { 
                doctor: doctorsId
            }
        },
        { 
            $group: {
            _id: null, 
            averageRating: { $avg: "$rating" },
            count: { $sum: 1 }
            } 
        },{$project:{_id:0, rating:"$averageRating", __v:"$count"}}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-10
      • 1970-01-01
      • 2020-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多