MongoDB使用聚合平均结果

时间:2016-06-24 18:20:18

标签: mongodb mongoose mongodb-query

我有一组看起来像这样的文件:

var schema = new Schema({
name: {type: String, required: true},
gradeLevels: {type: String},
subject: {type: String},
standard: {type: String},
description: {type: String},
price: {type: String},
numberOfInternalReviews: {type: Number},
reviews: [{
    content: {type: String},
    rating: {type: Number},
    user: {type: Schema.Types.ObjectId, ref: 'User'},
    userFirstName: {type: String},
    softDelete: {type : Boolean}
}],
averageUserRating: {type: Number}
});

我让他们创建了一个汇总公式,生成每个评论的平均评分,如下:

db.applications.aggregate([
      { $unwind: "$reviews" }, 
      { $group: { _id: "$_id", reviews: { $push: "$reviews" },                                       
                 averageUserRating: { $avg: "$reviews.rating" } } }, 
      { $project: { _id: 0, _id: "$_id", reviews: 1, averageUserRating: 1 } }]);

这确实会在控制台中根据需要生成平均值的正确结果。

我需要将结果推送到原始对象的averageUserRating字段。

当我查看应用程序文档时,averageUserRating仍然返回null。

我怎样才能实现这一目标?

1 个答案:

答案 0 :(得分:0)

也许它是一个类型的inb项目,所以:改变这个:

{ $project: { _id: 0, _id: "$_id", reviews: 1, averageUserRating: 1 } }]);

到:

{ $project: { _id: "$_id", reviews: 1, averageUserRating: 1 } }]);