Mongo聚合:返回数组值的总平均值

Posted

技术标签:

【中文标题】Mongo聚合:返回数组值的总平均值【英文标题】:Mongo aggregate: return total average of array values 【发布时间】:2017-06-05 14:34:31 【问题描述】:

我在 mongodb 中有这个数据

 
  "name": "FooBar",
  "__v": 0,
  "user_rating": [
  
    "date": "2017-06-02T16:19:32.002Z",
    "user_rating": 5,
  ,
  
    "date": "2017-06-02T16:19:46.803Z",
    "user_rating": 3,
  ,
  
    "date": "2017-06-02T16:20:01.244Z",
    "user_rating": 5,
  ,
  
    "date": "2017-06-02T16:15:54.673Z",
    "user_rating": 3,
  ,
  
    "date": "2017-06-02T16:53:42.489Z",
    "user_rating": 5,
  
 ]

我需要对此进行过滤以显示商店名称、平均评分、评分总数以及 5 个评分、4 个评分等。

这是我所期待的:

[
  
    "_id":"FooBar",
    "countRating":5,
    "averageRating":4.2,
    "ratings": [
       "num":3,"count":2,
       "num":5,"count":3
     ]
  
 ]

但是,我似乎无法获得averageRating - 相反,我获得了每个评分的两个总和的平均值。

这是我的 Mongo 查询:

 db.collection.aggregate([
      
        $match: "name": "FooBar"
      ,
      
          $unwind: "$user_rating"
      ,
      
        $match: "name": "FooBar"
      ,
        
          $group: 
            _id: 
              "name": "$name",
              "rating": "$user_rating.user_rating"
            ,
            averageRating: $avg: "$user_rating.user_rating",
            countRating: $sum: 1
        
      ,
      
        $group: 
          _id: "$_id.name",
          countRating: "$sum": "$totalRatings",
          averageRating: "$avg": "$averageRating",
          "rating": 
            "$push": 
              "num": "$_id.rating",
              "count": "$totalRatings"
            
          ,
        
      ]);

任何人都可以帮助获得这里的总体平均值吗? 谢谢!!

【问题讨论】:

【参考方案1】:
db.collection.aggregate([
       $match: "name": "FooBar" ,
       $unwind: "$user_rating" ,
      
          $group: 
              _id : "$name",
              avg: $avg: "$user_rating.user_rating" ,
              ratings: $push: "$user_rating.user_rating" 
          
      ,
       $unwind: "$ratings" ,
       
          $group: 
              _id:  name: "$_id", num: "$ratings", avg: "$avg" ,
              count:  $sum: 1               
          
      ,
      
          $group: 
              _id:  name: "$_id.name", avg: "$_id.avg" ,
              ratings:  $push:  num: "$_id.num", count: "$count" 
          
      ,
       $project: _id:0, name:"$_id.name", averageRating: "$_id.avg", ratings: 1
 ])

我在这里使用了额外的分组来计算总平均评分。然后我展开结果并在分组键中传递计算的平均值。

输出:


    "name" : "FooBar",
    "averageRating" : 4.2,
    "ratings" : [ 
        
            "num" : 3,
            "count" : 2
        , 
        
            "num" : 5,
            "count" : 3
        
    ]

【讨论】:

我怎样才能返回一个包含所有评分的数组?并且还添加分页以限制返回的数量@sergey-berezovskiy

以上是关于Mongo聚合:返回数组值的总平均值的主要内容,如果未能解决你的问题,请参考以下文章

SqlServer函数的聚合函数

21.MySQL中的聚合函数

mongodb 聚合 - 匹配 $nin 数组正则表达式值

mongo 使用聚合合并字段

mongo 使用聚合合并字段

MySQL的聚合函数