本文介绍了一键汇总和累加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难解释我想要得到什么,所以我将举一个例子:

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

我有对象:

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

我可以做到:

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

我会得到:

史蒂夫(Steve)获得了130个(100 +30)

Steve received 130 (100 +30)

卡罗琳娜收到了70

安德鲁(Andrew)收到10

Andrew received 10

但是我需要这样的东西:

史蒂夫(Steve)获得了130个(100 +30)

Steve received 130 (100 +30)

其他人都收到了80个(70 + 10)

Everyone else received 80 (70+10)

如何获得这种效果?

推荐答案

您可以在分组中使用 $ sum 累加器指定条件:

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 }
  }
] )

上面的聚合返回: {"steve_received":130,"others_received":80}

这篇关于一键汇总和累加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-24 17:46