The field “$name” must be an accumulator object

醉酒当歌 提交于 2020-05-10 10:14:19

问题


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
  }
])...

回答1:


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




回答2:


db.faq_feedback.aggregate({ 
   $lookup:{ 
      "from":"faq",
      "localField":"question_id",
      "foreignField":"_id",
      "as":"faq"
   }
},
{ 
   $unwind:"$faq"
},

{ 
   $project:{ 
      "question_id":1,
      "lang":"$faq.lang",
      "feedback":"$faq.feedback",
      "question":"$faq.question",
      "yes":{ 
         "$cond":[ 
            { 
               "$eq":[ 
                  "$feedback",
                  "yes"
               ]
            },
            1,
            0
         ]
      },
      "no":{ 
         "$cond":[ 
            { 
               "$eq":[ 
                  "$feedback",
                  "no"
               ]
            },
            1,
            0
         ]
      }
   }
},

{ 
   $group:{ 
      "_id":"$question_id",

      "yes":{ 
         "$sum":"$yes"
      },
      "no":{ 
         "$sum":"$no"
      },
      "question":{"$first":"$question"},
      "lang":{"$first":"$lang"}
   }
},
{ 
   $limit:10000
},
{ 
   $skip:0
})



回答3:


$group: {
    _id:"$_id", 
    "name" :{ $last: '$name' }, 
    "count" : { $sum: 1 }, 
    "totalValue": { "$sum": "$value" }
}


来源:https://stackoverflow.com/questions/54440636/the-field-name-must-be-an-accumulator-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!