我有一个文档集合,看起来像这样:
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。
我该怎么做?
也许它是一个type inb项目,所以:修改这个:
{ $project: { _id: 0, _id: "$_id", reviews: 1, averageUserRating: 1 } }]);
:
{ $project: { _id: "$_id", reviews: 1, averageUserRating: 1 } }]);