Aggregate,Mongoose - 忽略重复的结果

时间:2018-05-10 05:41:13

标签: mongodb mongoose aggregation-framework

我有以下架构

var reviewSchema = new Schema({
    restaurantID: ObjectId,
    rating: {
     food: Number,
     service: Number,
     value: Number
    },
});

我希望获得一系列平均食物,评级,服务等级,以便我做到

 Review.aggregate([
                    {
                        $match: {
                            restaurantID: mongoose.Types.ObjectId(reviewData.restaurantid)
                        }
                    },
                    {
                        $unwind: "$rating"
                    },
                    {
                        $group:{
                            _id: "$rating",
                            total_rating: { $avg: { $add: [ "$rating.food", "$rating.service", "$rating.value" ] } }
                        }
                    }
 ], function(review_error, reviews) {

然而,首先,它没有获得三个字段的平均值,它只获得字段的总和。没关系,我可以把它除以3。最大的问题是它忽略了重复的结果。我试图将结果打印出来:

 [ { _id: { food: 4, service: 5, value: 4 }, total_rating: 13 },
  { _id: { food: 5, service: 5, value: 5 }, total_rating: 15 } ]

我在集合中有6条{ _id: { food: 5, service: 5, value: 5 }, total_rating: 15 }条记录。我该如何解决这个问题?谢谢!

已更新:示例

评论收藏

{ 
    "_id" : ObjectId("5af3d804d0d09e18b098208f"), 
    "rating" : {
        "food" : NumberInt(5), 
        "service" : NumberInt(5), 
        "value" : NumberInt(5)
    }, 
    "restaurantID" : ObjectId("5ac962bd437c1e30e89406a8"), 
}
{ 
    "_id" : ObjectId("5af3d817d0d09e18b0982090"), 
    "rating" : {
        "food" : NumberInt(5), 
        "service" : NumberInt(5), 
        "value" : NumberInt(5)
    }, 
    "restaurantID" : ObjectId("5ac962bd437c1e30e89406a8"), 
}
{ 
    "_id" : ObjectId("5af3d89161cc0a0e60f0925d"), 
    "rating" : {
        "food" : NumberInt(4), 
        "service" : NumberInt(5), 
        "value" : NumberInt(4)
    }, 
    "restaurantID" : ObjectId("5ac962bd437c1e30e89406a8"), 
}

预期结果

[ { _id: { food: 5, service: 5, value: 5 }, total_rating: 15 },
  { _id: { food: 4, service: 5, value: 4 }, total_rating: 13 },
  { _id: { food: 5, service: 5, value: 5 }, total_rating: 15 } ]

实际结果

   [ { _id: { food: 4, service: 5, value: 4 }, total_rating: 13 },
     { _id: { food: 5, service: 5, value: 5 }, total_rating: 15 } ]

0 个答案:

没有答案