Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 437
Roy Reznik Avatar asked May 21 '13 17:05

Roy Reznik


People also ask

How do I sum fields in MongoDB?

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 .

Can we specify more than one aggregate function simultaneously in MongoDB?

Db. collection. aggregate () can use several channels at the same time for data processing.

How do you add a field in aggregate?

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 .

What is aggregation framework in MongoDB?

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.


1 Answers

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' ] },      } 
like image 181
Roy Reznik Avatar answered Sep 28 '22 09:09

Roy Reznik