Many-to-many with references in MongoDB - Time & Space Complexity
When working with many-to-many relationships in MongoDB using references, it's important to understand how the time to get data grows as the number of linked items grows.
We want to know how the number of operations changes when fetching related data from multiple collections.
Analyze the time complexity of the following code snippet.
// Find all students and their courses
const students = db.students.find().toArray();
for (const student of students) {
const courses = db.courses.find({ _id: { $in: student.courseIds } }).toArray();
// process student with courses
}
This code fetches all students, then for each student fetches all courses they are linked to by IDs.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping over each student and querying courses for each.
- How many times: Once per student, and inside that, a query for their courses.
As the number of students grows, the number of course queries grows too, since each student triggers a separate query.
| Input Size (n students) | Approx. Operations |
|---|---|
| 10 | 1 student query + 10 course queries |
| 100 | 1 student query + 100 course queries |
| 1000 | 1 student query + 1000 course queries |
Pattern observation: The total operations grow roughly in direct proportion to the number of students.
Time Complexity: O(n)
This means the time to fetch all students and their courses grows linearly with the number of students.
[X] Wrong: "Fetching courses for all students is just one query, so it's constant time regardless of students."
[OK] Correct: Each student's courses are fetched separately, so the number of queries grows with students, making the total time grow too.
Understanding how many queries run and how they grow with data size is a key skill. It helps you design better data fetching strategies and explain your choices clearly.
"What if we changed the code to fetch all courses for all students in a single query instead of one per student? How would the time complexity change?"
Practice
Solution
Step 1: Understand many-to-many references
In MongoDB, many-to-many means each document in one collection can link to many documents in another, and vice versa.Step 2: Identify how references are stored
This is done by storing arrays of IDs in both collections, so each side knows its related documents.Final Answer:
Both collections store arrays of IDs pointing to each other. -> Option CQuick Check:
Many-to-many references = arrays of IDs in both collections [OK]
- Thinking only one side stores references
- Confusing many-to-many with embedding all data
- Assuming data is duplicated without IDs
students and courses collections in MongoDB?Solution
Step 1: Check reference format
References must be arrays of IDs to represent many-to-many links.Step 2: Validate { _id: 1, name: 'Alice', courses: [101, 102] } and { _id: 101, title: 'Math', students: [1, 2] }
{ _id: 1, name: 'Alice', courses: [101, 102] } and { _id: 101, title: 'Math', students: [1, 2] } shows arrays of IDs in both collections, correctly linking students and courses.Final Answer:
{ _id: 1, name: 'Alice', courses: [101, 102] } and { _id: 101, title: 'Math', students: [1, 2] } -> Option BQuick Check:
Arrays of IDs in both collections = correct syntax [OK]
- Using single ID instead of array for many-to-many
- Storing names instead of IDs as references
- Leaving reference arrays empty without reason
{ _id: 1, name: 'Bob', courses: [201, 202] }{ _id: 201, title: 'History', students: [1, 3] }What will be the result of querying the
courses array for student with _id: 1?Solution
Step 1: Identify the student's courses field
The student document with _id 1 has a courses array: [201, 202].Step 2: Understand the query result
Querying the courses array for this student returns the IDs [201, 202], not titles or student IDs.Final Answer:
[201, 202] -> Option DQuick Check:
Student's courses array = [201, 202] [OK]
- Confusing course IDs with student IDs
- Expecting course titles instead of IDs
- Assuming empty array if unsure
students: { _id: 2, name: 'Eve', courses: [301] }courses: { _id: 301, title: 'Science', students: [] }What is the problem with this many-to-many reference setup?
Solution
Step 1: Check references in both collections
The student document lists course 301, but the course document's students array is empty.Step 2: Identify missing reciprocal reference
For many-to-many, both sides must reference each other. The course's students array should include student ID 2.Final Answer:
The students array in courses is missing the student ID. -> Option AQuick Check:
Both sides must reference each other [OK]
- Ignoring missing reciprocal references
- Assuming one side is enough
- Confusing empty arrays with missing fields
Solution
Step 1: Understand the query goal
We want students enrolled in both courses 401 and 402, so their courses array must contain both IDs.Step 2: Choose correct MongoDB operator
The $all operator matches arrays containing all specified elements, perfect for this case.Final Answer:
{ $match: { courses: { $all: [401, 402] } } } -> Option AQuick Check:
$all matches arrays containing all elements [OK]
- Using $in matches any, not all elements
- Using $size only checks array length, not content
- Matching single course ID misses the second course
Ready to prove it?
Pass the test and this pattern moves unknown
