The field must be an accumulator object in mongo [duplicate]

跟風遠走 提交于 2019-12-24 11:20:06

问题


I am performing an aggregation query.My requirement is that I have docs in following format:

{
"name":"a","age":20},
{
"name":"b","age":23},
{
"name":"a","age":26}

I need to sum the ages of all names who have "a" in their name field. I am doing the following but it gives me an error that "The field 'name' must be an accumulator object":

db.collection('students').aggregate({
        $group: {"name": "a", "sum": {$sum: '$age'}}
    }, {
        $project: {sum: '$sum'}
    }, (e, d) => {
        if (!e) {
            var e = d.stream({transform: JSON.stringify});
            console.log("answer")
            console.log(e);
            deferred.resolve(e);
        } else {
            console.log(e)
        }
    })

回答1:


I altered your aggregation query.Try as below:

db.collection('students').aggregate(
     [
       {
          $match: {
                 name: "a"
          }
       },
       {
         $group: {_id: "$name",
                  "sum": {
                     $sum: '$age'
                   }
                 }
        },
        {
          $project: {
                 sum: 1
        }
     ], (e, d) => {
        if (!e) {
            var e = d.stream({transform: JSON.stringify});
            console.log("answer")
            console.log(e);
            deferred.resolve(e);
        } else {
            console.log(e)
        }
    })



回答2:


Here, you are missing match filter properly. We should use $match filter to find out specific results and "_id" for attribute on which we are performing operation in $group.

Structure of your query would be -

db.students.aggregate(
[
    {
        $match: {
            "name": "a"
        }
    },
    {
        $group: {
            "_id": "$name",
            totalTte: {
                $sum: "$age"
            }
        }
    },
    {
        $project: {
            sum: 1
        }
    }
])


来源:https://stackoverflow.com/questions/54823617/the-field-must-be-an-accumulator-object-in-mongo

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