Roy Reznik
Roy Reznik

Reputation: 2110

Is it possible to sum 2 fields in MongoDB using the Aggregation framework?

I have a collection with documents that contain fields type, totalA and totalB

I want to use the aggregation framework in order to group by type - and get the sum of both totalA and totalB together.

The last thing I tried (doesn't work) is:

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

totalSum has the sum of only one of the fields instead of the combined value.

Upvotes: 27

Views: 43644

Answers (3)

Manohar Reddy Poreddy
Manohar Reddy Poreddy

Reputation: 27395

In addition to this answer here, had issue with $add giving wrong values, when keys are not present in some documents.

If, for example, Col3 & Col4 keys are sometimes not present/ undefined, then below $ifNull will help:

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

Upvotes: 22

Dobrea Petrisor
Dobrea Petrisor

Reputation: 501

You can use $sum in this way:

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

Upvotes: 39

Roy Reznik
Roy Reznik

Reputation: 2110

I found a solution:

Just using $project to $add the two fields together in the output.

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

Upvotes: 64

Related Questions