The field must be an accumulator object in mongo

10,282

Solution 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)
        }
    })

Solution 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
        }
    }
])
Share:
10,282

Related videos on Youtube

Akshay
Author by

Akshay

Updated on June 04, 2022

Comments

  • Akshay
    Akshay about 2 years

    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)
            }
        })
    
  • Akshay
    Akshay over 5 years
    Thanks bro! It worked.
  • Akshay
    Akshay over 5 years
    yes you are right.I figured it out anyway.Thanks for pointing though.