MongoError: The field ‘academic_year’ must be an accumulator object

Total
1
Shares

I have the following aggregation code which returns all the students for each school in my school ID list. For each student there is an academic year ID that looks like this: ObjectId("5ede4682341e8426f1cf6285")

return await this.studentSchoolModel.aggregate([
      {
        $match: {
          school: { $in: schoolIDs },
        },
      },

      {
        $group: {
          _id: '$school',
          academic_years: '$academic_year',
          total_students: { $sum: 1 },
        },
      },
    ]);

If I try to group by the school, it works, but if I try to group by the school and academic year I get the following error:

MongoError: The field 'academic_year' must be an accumulator object

Does anyone know what I’m doing wrong? I want the output for each school to look like this:

_id: 12345678 //schoolID
academic_years: {
          _id: 1111111 //academic year ID
          total_students: 5 //number of students in that year
          },
          {
          _id: 2222222 //academic year ID
          total_students: 8 //number of students in that year
          }

Solution

You can use $group

  • first group is to group by school and academic year. The second group is to group by school

Here is the code

db.collection.aggregate([
  {
    "$group": {
      "_id": { sc: "$school", ay: "$academic_year" },
      total: { $sum: 1 }
    }
  },
  {
    $group: {
      _id: "$_id.sc",
      total_students: {
        $push: {
          _id: "$_id.ay",
          total_students: "$total"
        }
      }
    }
  }
])

Working Mongo playground

Leave a Reply

Your email address will not be published. Required fields are marked *