How to get sum of results got from aggegate group query with first operator

I am using mongodb with ODM & PHP symfony,

Retrieving a set of data with aggregate query builder and group function, using ->first operator , i’m retrieving first elements of grouped data wit DESC of ceated date, i need sum of one of the fields in this grouped data in a single query.

It would be helpful to share a few example documents from the collection (feel free to redact irrelevant fields) and another example of the output you’re trying to produce.

I’m not sure what “using ->first operator” refers to. Are you referring to the Doctrine ODM builder method that corresponds to a $first accumulator in the MongoDB query language?

The $sum documentation in the MongoDB server manual has some examples of using $sum with $group. See: Use in $group Stage.

If you’re using Doctrine MongoDB ODM, there is also an example of using $group and $sum in the Aggregation Builder documentation. The examples don’t happen to show first(), but it can be used within a group() context similar to sum() and other accumulator methods.

Before you attempt to create this query via the ODM’s aggregation builder I think it would be more helpful/educational to try and construct the raw aggregation pipeline and execute it via the MongoDB shell. This will allow you to work alongside examples in the MongoDB server manual. Doctrine ODM’s documentation is not a replacement for server manual, especially when it comes to MongoDB’s query language.

Alternatively, MongoDB Compass includes a visual Aggregation Pipeline Builder that may be helpful. That should allow you to iteratively construct an aggregation pipeline while connected to your database, which you can then port over to ODM’s builder methods once you’re satisfied.

1 Like