Aggregate and sum by one key and rest

谁说胖子不能爱 提交于 2021-02-04 08:27:36

问题


It's hard for me to explain what I want to get, so I will show an example:

I have objects:

{name: 'steve', received: 100} {name: 'carolina', received: 70} 
{name: 'steve', 'received: 30} {name: 'andrew', received: 10}

I can do:

    { $group :
         { _id : '$name',
           sum : { "$sum" :'$received' }, 
         },                          
    },

And i will get:

Steve received 130 (100 +30)

Carolina received 70

Andrew received 10

But I need something like that:

Steve received 130 (100 +30)

Everyone else received 80 (70+10)

How can I get this effect?


回答1:


You can specify a condition with the $sum accumulator operator in the grouping:

db.test.aggregate( [
  { 
      $group : { 
          _id :  null, 
          steve_received: { 
              $sum: {
                  $cond: [ { $eq: [ "$name", "steve" ] }, "$received", 0 ]
              } 
          },
          others_received: { 
              $sum: {
                  $cond: [ { $ne: [ "$name", "steve" ] }, "$received", 0 ]
              } 
          }
      } 
  },
  {
      $project: { _id: 0 }
  }
] )

The above aggregation returns: { "steve_received" : 130, "others_received" : 80 }



来源:https://stackoverflow.com/questions/60311604/aggregate-and-sum-by-one-key-and-rest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!