0
0
MongoDBquery~10 mins

Many-to-many with references in MongoDB - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Many-to-many with references
Create Collection A
Create Collection B
Insert Documents in A with refs to B
Insert Documents in B
Query with $lookup to join
Get combined results
This flow shows how the students collection references the courses collection to model many-to-many relations, then how to query them together.
Execution Sample
MongoDB
db.students.insertMany([
  {_id: 1, name: "Alice", courses: [101, 102]},
  {_id: 2, name: "Bob", courses: [102, 103]}
]);
db.courses.insertMany([
  {_id: 101, title: "Math"},
  {_id: 102, title: "History"},
  {_id: 103, title: "Science"}
]);
Insert students and courses with references to model many-to-many relationships.
Execution Table
StepActionCollectionDocument Inserted/UpdatedResulting State
1Insert student Alicestudents{"_id":1, "name":"Alice", "courses":[101,102]}students: [{_id:1, name:'Alice', courses:[101,102]}]
2Insert student Bobstudents{"_id":2, "name":"Bob", "courses":[102,103]}students: [{_id:1,...}, {_id:2, name:'Bob', courses:[102,103]}]
3Insert course Mathcourses{"_id":101, "title":"Math"}courses: [{_id:101, title:'Math'}]
4Insert course Historycourses{"_id":102, "title":"History"}courses: [{_id:101,...}, {_id:102, title:'History'}]
5Insert course Sciencecourses{"_id":103, "title":"Science"}courses: [{_id:101,...}, {_id:102,...}, {_id:103, title:'Science'}]
6Query students with course details using $lookupstudentsAggregation with $lookup on coursesResult: Each student document includes course info for referenced course IDs
7Exit--All documents inserted and joined successfully
💡 All inserts done and join query executed to combine related documents.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4After Step 5After Step 6Final
students[][{_id:1, name:'Alice', courses:[101,102]}][{_id:1,...}, {_id:2, name:'Bob', courses:[102,103]}][{_id:1,...}, {_id:2,...}][{_id:1,...}, {_id:2,...}][{_id:1,...}, {_id:2,...}][{_id:1,..., coursesInfo:[{_id:101,...},{_id:102,...}]}, {_id:2,..., coursesInfo:[{_id:102,...},{_id:103,...}]}][{_id:1,..., coursesInfo:[...]} , {_id:2,..., coursesInfo:[...]}]
courses[][][][{_id:101, title:'Math'}][{_id:101,...}, {_id:102, title:'History'}][{_id:101,...}, {_id:102,...}, {_id:103, title:'Science'}][{_id:101,...}, {_id:102,...}, {_id:103,...}][{_id:101,...}, {_id:102,...}, {_id:103,...}]
Key Moments - 3 Insights
Why do we store arrays of course IDs in student documents instead of embedding full documents?
Storing only IDs keeps documents small and avoids duplication. The execution_table step 6 shows how $lookup joins data at query time.
How does $lookup know which documents to join?
$lookup matches the array of IDs in students.courses with courses._id as shown in execution_table step 6, combining related documents.
What happens if a referenced course ID does not exist?
The $lookup will return an empty array for that course reference, so the student document will have fewer joined course details.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 2. What is the courses array for student Bob?
A[101, 102]
B[102, 103]
C[101, 103]
D[]
💡 Hint
Check the 'Document Inserted/Updated' column at step 2 in execution_table.
At which step do we insert the course titled 'History'?
AStep 4
BStep 3
CStep 5
DStep 6
💡 Hint
Look at the 'Action' and 'Document Inserted/Updated' columns in execution_table.
If we remove course ID 102 from Alice's courses array, what changes in variable_tracker after step 6?
AAlice's coursesInfo will be empty
BAlice's coursesInfo will include courses 101 and 102 details
CAlice's coursesInfo will include only course 101 details
DNo change in coursesInfo
💡 Hint
Refer to variable_tracker row for 'students' after step 6 showing coursesInfo arrays.
Concept Snapshot
Many-to-many with references in MongoDB:
- Store arrays of course IDs in student documents.
- Use $lookup aggregation to join related documents.
- Keeps data normalized and queries flexible.
- Example: students have courses array of course IDs.
- Query joins students with course details by matching IDs.
Full Transcript
This visual execution shows how to model many-to-many relationships in MongoDB using references. We create two collections, students and courses. Each student document stores an array of course IDs they attend. Each course document stores its details. We insert sample students and courses. Then we use the $lookup aggregation stage to join students with their course documents by matching course IDs. The execution table traces each insert and the join query step-by-step. The variable tracker shows how the students and courses collections grow and how the joined results include course details. Key moments clarify why we store IDs instead of full documents and how $lookup works. The quiz tests understanding of the data at each step. This method keeps data normalized and queries efficient for many-to-many relations.