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.
If used on a field that contains both numeric and non-numeric values, $sum ignores the non-numeric values and returns the sum of the numeric values. If used on a field that does not exist in any document in the collection, $sum returns 0 for that field. If all operands are non-numeric, $sum returns 0 .
Db. collection. aggregate () can use several channels at the same time for data processing.
You can include one or more $addFields stages in an aggregation operation. To add field or fields to embedded documents (including documents in arrays) use the dot notation. See example. To add an element to an existing array field with $addFields , use with $concatArrays .
Aggregation in MongoDB allows for the transforming of data and results in a more powerful fashion than from using the find() command. Through the use of multiple stages and expressions, you are able to build a "pipeline" of operations on your data to perform analytic operations.
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' ] }, }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With