Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The field "$name" must be an accumulator object

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   } ])... 
like image 338
Matheus Barem Avatar asked Jan 30 '19 12:01

Matheus Barem


People also ask

What is accumulator object?

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.

What is $$ root in MongoDB?

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.

What is $first in MongoDB?

This means $first returns the first order type for the documents between the beginning of the partition and the current document.

What is $project in MongoDB?

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.


1 Answers

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

like image 85
Ashh Avatar answered Sep 28 '22 01:09

Ashh