I have a query and when I use a $group a error shows "the field "$name must be an accumulator object", if if remove the filed "$name" all works well and i have tried to use only "name" instead of "$name" and the error continues.
User.aggregate([ { $match: { "storeKey": req.body.store } }, { $group: { "_id": "$_id", "name": "$name", "count": { "$sum": 1 }, "totalValue": { "$sum": "$value" } } }, { $sort: sort }, { $skip: req.body.limit * req.body.page }, { $limit: req.body.limit } ])...
Accumulators are operators that maintain their state (e.g. totals, maximums, minimums, and related data) as documents progress through the pipeline. Use the $accumulator operator to execute your own JavaScript functions to implement behavior not supported by the MongoDB Query Language.
The $$ROOT variable contains the source documents for the group. If you'd like to just pass them through unmodified, you can do this by $pushing $$ROOT into the output from the group.
This means $first returns the first order type for the documents between the beginning of the partition and the current document.
Definition. $project. Passes along the documents with the requested fields to the next stage in the pipeline. The specified fields can be existing fields from the input documents or newly computed fields.
There are some aggregation operators that can only be used in $group
aggregation and named as $group accumulators
Just as you used $sum
here you have to use for the name
key as well
{ "$group": { "_id": "$_id", "name": { "$first": "$name" }, //$first accumulator "count": { "$sum": 1 }, //$sum accumulator "totalValue": { "$sum": "$value" } //$sum accumulator }}
Accumulator is like array of Elements its Accumulates as Array. $first -> gives 1st name that goes in the group of names
Example: so if you have $_id
same but different name ["Darik","John"]
specifying $first
will give Darik & similarly $last
will give John
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