The field "$name" must be an accumulator object
69,359
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
Comments
-
Matheus Barem over 4 years
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 } ])...