【问题标题】:How to get average value using aggregation in Mongoose?如何在 Mongoose 中使用聚合获得平均值?
【发布时间】:2018-12-01 21:00:15
【问题描述】:

我有一个 Mongoose 架构,其中一个属性定义如下:

// Partially removed for brevity.
const recommendationsSchema = new mongoose.Schema({
  ratings: [{ category: String, rating: Number }],
}, {
  timestamps: true
});

现在我想获取我收藏中的条目总数,以及评分的平均值。但是,我只想获得category 字段等于total 的评分的平均值。比如{ category: 'total' }

我试图做这样的事情,但似乎没有用:

[
    {
        $count: "total_count",
        $group: {
            avg: { $avg: $ratings.rating }
        }
    }
]

count 字段似乎返回集合中的总条目,这很好,也是我想要的。但是,我怎样才能得到{ category: 'total' } 的平均收视率?所以,我只想返回两个字段,total_countaverage。任何想法如何在 Mongoose 中实现这一目标?

【问题讨论】:

    标签: mongodb mongoose mongodb-query aggregation-framework


    【解决方案1】:

    你可以使用下面的聚合

    db.collection.aggregate([
      { "$facet": {
        "totalCount": [{ "$count": "count" }],
        "averagteRating": [
          { "$match": { "ratings.category": "total" } },
          { "$unwind": "$ratings" },
          { "$match": { "ratings.category": "total" } },
          { "$group": {
            "_id": null,
            "averageRating": { "$avg": "$ratings.rating" }
          }}
        ]
      }}
    ])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多