27

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.

3 Answers 3

64

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' ] },
     }
Sign up to request clarification or add additional context in comments.

Comments

40

You can use $sum in this way:

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

Comments

22

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.