Skip to content
Advertisement

MongoDB get sum of fields in last stage of aggregate

I’m using an aggregate to gather some related data. The following is a sample pipeline that joins a Parent Collection to a Children One (Each Parent will have a Child).

I then use a projection to gather some fields from both collections. This includes getting a count of the “number of sodas” a child has.

Ultimately, I’m aiming to get a total of all the sodas that all children have (So basically a summation of the childSodaCount field in the projection.

I attempted this by appending a group stage at the end of the pipeline. THis does work, however, I lose all the other fields from the projection.

Any insights?

JavaScript

Advertisement

Answer

Basically $group by null will group all documents in a single document, Try $facet to separate both result after $project stage,

JavaScript

This will result something like,

JavaScript

If you want to get direct count instead of array of object try $addFields stage after $facet stage,

JavaScript

Your final result will be,

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement