简体   繁体   中英

How to make a query in two different collections in mongoDB? (without using ORM)

Suppose, In MongoDB i have two collections. one is "Students" and the another is "Course".

Student have the document such as

{"id":"1","name":"Alex"},.. 

and Course has the document such as

{"course_id":"111","course_name":"React"},.. 

and there is a third collection named "students-courses" where i have kept student's id with their corresponding course id. Like this

{"student_id":"1","course_id":"111"}

i want to make a query with student's id so that it gives the output with his/her enrolled course. like this

{
  "id": "1", 
  "name":"Alex",
  "taken_courses": [
    {"course_id":"111","course_name":"React"}, 
    {"course_id":"112","course_name":"Vue"}
  ]
} 

it will be many to many relationship in MongoDB without using ORM. How can i make this query?

Need to use $loopup with pipeline,

  • First $group by student_id because we are going to get courses of students, $push all course_id in course_ids for next step - lookup purpose
db.StudentCourses.aggregate([
  {
    $group: {
      _id: "$student_id",
      course_ids: {
        $push: "$course_id"
      }
    }
  },
  • $lookup with Student Collection and get the student details in student
  • $unwind student because its an array and we need only one from group of same student record
  • $project required fields
  {
    $lookup: {
      from: "Student",
      localField: "_id",
      foreignField: "id",
      as: "student"
    }
  },
  {
    $unwind: "$student"
  },
  {
    $project: {
      id: "$_id",
      name: "$student.name",
      course_ids: 1
    }
  },
  • $lookup Course Collection and get all courses that contains course_ids , that we have prepared in above $group
  • $project the required fields
  • course details will store in taken_courses
  {
    $lookup: {
      from: "Course",
      let: {
        cId: "$course_ids"
      },
      pipeline: [
        {
          $match: {
            $expr: {
              $in: [
                "$course_id",
                "$$cId"
              ]
            }
          }
        },
        {
          $project: {
            _id: 0
          }
        }
      ],
      as: "taken_courses"
    }
  },
  • $project details, removed not required fields
  {
    $project: {
      _id: 0,
      course_ids: 0
    }
  }
])

Working Playground: https://mongoplayground.net/p/FMZgkyKHPEe

For more details related syntax and usage, check aggregation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM