Home > Back-end >  How would I make grouped lists through querying using MongoDB aggregation?
How would I make grouped lists through querying using MongoDB aggregation?

Time:11-21

Say that I have an attribute with something like letter grades of a student, using a structure like:

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

and 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 (hopefully without having to manually type each letter grade)?

I've tried $group-ing the students with grades and using $match to try and iterate through the list of grades, but I haven't come across any errorless ways of creating sets without just getting an integer count of how many students have that grade (ex. 7 students have grade of A . But who are the students?).

CodePudding user response:

If I understand what you are trying to do, here's one way to "$group" by "grades" and get an array of all "student_name" with that grade.

db.Students.aggregate([
  {
    "$group": {
      "_id": "$grades",
      "names": {"$push": "$student_name"},
      "count": {"$count": {}}
    }
  }
])

Try it on mongoplayground.net.

  • Related