Home > other >  Get students for given list of classes in mongodb
Get students for given list of classes in mongodb

Time:10-06

As specified below, I have section and class schema in my MongoDB.

How can I query all the students of a given list of Class IDs?

const sectionsSchema = new Schema({
    section: {
        type: String,
        required: false
    },
    students:[{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
    }]
})


const classSchema = new Schema({
    name:{
        type: String,
        required: true
    },
    institution: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Institution'
    },
    divisions :[{
        type: sectionsSchema,
        required: true
    }]
    
},{timestamps: true})

Below is the Example Data

Class: [{ _id: 'Class1', institution: 'inst1', divisions:[{ section: 'A', students: ['Stud1','Stud2'] }, { section: 'B', students: ['Stud3','Stud4'] }] }, { _id: 'Class2', institution: 'inst1', divisions:[{ section: 'A', students: ['Stud5','Stud6'] }] }]

    input: ['Class1','Class2'];
    Expected Output: ['Stud1','Stud2','Stud3','Stud4','Stud5','Stud6'];

CodePudding user response:

My suggestion is to use an aggregate query as following:

.aggregate([
  {
    $match: {
      _id: {
        $in: [
          "Class1",
          "Class2"
        ]
      }
    }
  },
  {
    $unwind: "$divisions"
  },
  {
    $unwind: "$divisions.students"
  },
  {
    "$replaceRoot": {
      "newRoot": "$divisions"
    }
  },
])

Example output:

[
  {
    "section": "A",
    "students": "Stud1"
  },
  {
    "section": "A",
    "students": "Stud2"
  },
  {
    "section": "B",
    "students": "Stud3"
  },
  {
    "section": "B",
    "students": "Stud4"
  },
  {
    "section": "A",
    "students": "Stud5"
  },
  {
    "section": "A",
    "students": "Stud6"
  }
]

You afterwards have to map the documents returned to simple strings, since mongoose is not able to return plain strings.

  • Related