【问题标题】:Is it possible to sum 2 fields in MongoDB using the Aggregation framework?是否可以使用聚合框架对 MongoDB 中的 2 个字段求和?
【发布时间】:2013-05-16 14:01:15
【问题描述】:

我有一个包含字段类型、totalA 和 totalB 的文档的集合

我想使用聚合框架按类型分组 - 并获得 totalA 和 totalB 的总和。

我尝试的最后一件事(不起作用)是:

'$group' : { 
  '_id' : '$type', 
  'totalA' : { '$sum' : '$totalA' },
  'totalB' : { '$sum' : '$totalB' },
  'totalSum' : { '$sum' : '$totalA', '$sum' : '$totalB' },
}  }

totalSum 仅具有一个字段的总和,而不是组合值。

【问题讨论】:

    标签: mongodb pymongo aggregation-framework


    【解决方案1】:

    我找到了解决办法:

    只需使用 $project 在输出中将两个字段 $add 在一起。

    { "$project" : {
          'totalA' : '$totalA',
          'totalB' : '$totalB',
          'totalSum' : { '$add' : [ '$totalA', '$totalB' ] },
         }
    

    【讨论】:

      【解决方案2】:

      你可以这样使用$sum

      {
          $group : {
              _id: null,
              amount: { $sum: { $add : [ 
                  '$NumberOfItemsShipped', '$NumberOfItemsUnshipped' 
              ]}},
          }
      },
      

      【讨论】:

        【解决方案3】:

        除了这里的answer 之外,还添加了$add 在某些文档中不存在键时给出错误值的问题。

        例如,如果 Col3Col4 键有时是 not present/ undefined,那么下面的 $ifNull 会有所帮助:

        {
         $group : {
          _id: {
             "Col1": "$Col1",
             "Col2": "$Col2"
            },
          sum_of_all_days_in_year: {
            $sum: {
              "$add": [
                { "$ifNull": ["$Col3", 0] },
                { "$ifNull": ["$Col4", 0] }
               ]
             }
          },
         }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-07-23
          • 1970-01-01
          • 1970-01-01
          • 2013-03-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多