Listing through Querying (aggregation?)

Hi guys, say I’m using MongoDB standard and I have an attribute with something like letter grades of a student using a structure like:

    "_id": {
        "$oid": string
    "student_id": int,
    "grades": string,
    "student_name": string,

I want to go through the database and group the students by storing them in sets based on each letter grade (assuming that each student has a unique name) like:
A+ : [Chris, Ada, Lee], A- : [John, Lisa], …
How would I structure the query through using something like addToSet() (without having to manually type each letter grade)?

Hi @Owen_Shi ,

You can use the $group stage with a $addToSet operator:

db.collection.aggregate([{$group: {
                  _id : "$grades",
                  student_names : { $addToSet: "$student_name"}}}])


This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.