Search code examples
mongodbmongodb-querynosqlmongoose-schema

How to get all the students of a department in Mongoose MongoDb


I am an amateur in MongoDB, trying to build an educational database.

I have two document models: 1) Department 2) Student

Each Student document has ref: Department with its _id.

So, If I have the Department _id, how can I find all the students it has?

const department = mongoose.schema({
  name: { type: String } 
})
const student = mongoose.schema({
  name: { type: String },
  department: { mongoose.Schema.Types.ObjectId, ref: Department}
})

Solution

  • You only need to use $lookup like this:

    Using this $lookup you are telling mongo "give me all documents from student collection where its department field is like _id field in department collection and create an array called departmens with these values.

    yourDepartmentModel.aggregate([
      {
        "$lookup": {
          "from": "student",
          "localField": "_id",
          "foreignField": "department",
          "as": "departments"
        }
      }
    ])
    

    Example here