Grouping within arraythen converting it to object

I have a single document of the below format, which has an array. How can I use aggregation framework to get the output as an object which has field name as value of “name” and field value as an array of all the grades for that particular name?

Hi @Sreekanth_R_Shekar ,
You can use this:

db.collection.aggregate(
[{
    $addFields: {
        students: {
            $function: {
                body: function(students) {
                    let retVal = {};
                    for (let student of students) {
                        if (!retVal[student.name]) {
                            retVal[student.name] = []
                        }
                        retVal[student.name].push(student.grade)
                    }
                    return retVal;
                },
                args: ["$students"],
                lang: "js"
            }
        },
    }
}])

Good luck,
Rafael,

Thank you, but my version is mongoDB 4.2.8 and hence I cannot use “$function”. Is there any workaround for this?

try this:

[{$unwind: {
  path: "$students"
}}, {$group: {
  _id: {
    _id: "$_id",
    class: "$class",
    name: "$students.name"
  },
  grades: {
    $push: "$students.grade"
  }
}}, {$group: {
  _id: "$_id._id",
  class: {
    $first: "$_id.class"
  },
  students: {
    $push: {k: "$_id.name", v: "$grades"}
  }
}}, {$addFields: {
  students: {
    $arrayToObject: "$students"
  }
}}]

Thanks,
Rafael,

1 Like