One-to-many referencing pattern in MongoDB - Time & Space Complexity
When using one-to-many referencing in MongoDB, we want to know how the time to get data changes as the number of related items grows.
We ask: How does fetching a document and its related many documents scale with more data?
Analyze the time complexity of the following code snippet.
// Find a user by ID
const user = db.users.findOne({ _id: userId });
// Find all posts referencing this user
const posts = db.posts.find({ userId: user._id }).toArray();
This code fetches one user and then fetches all posts linked to that user by userId.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Scanning all posts that match the userId.
- How many times: Once for the user, then once for each post linked to that user.
As the number of posts for a user grows, the time to fetch all posts grows roughly the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 posts | About 10 operations to fetch posts |
| 100 posts | About 100 operations to fetch posts |
| 1000 posts | About 1000 operations to fetch posts |
Pattern observation: The time grows directly with the number of posts linked to the user.
Time Complexity: O(n)
This means the time to get all related posts grows linearly with how many posts there are for that user.
[X] Wrong: "Fetching related posts is always fast no matter how many posts exist."
[OK] Correct: The more posts linked to a user, the longer it takes to fetch them all, so time grows with data size.
Understanding how fetching related data scales helps you explain database design choices clearly and shows you think about real data growth.
"What if we stored all posts inside the user document instead of referencing? How would the time complexity change when fetching posts?"
Practice
Solution
Step 1: Understand one-to-many referencing
It connects one document to many others by storing their IDs, not embedding all data.Step 2: Compare options
Only To link one document to many related documents using their IDs describes linking documents by IDs, which is the core of one-to-many referencing.Final Answer:
To link one document to many related documents using their IDs -> Option CQuick Check:
One-to-many referencing = linking documents by IDs [OK]
- Thinking all data is stored inside one document
- Confusing referencing with embedding
- Assuming it creates backups automatically
comments in a post document using one-to-many referencing in MongoDB?Solution
Step 1: Identify referencing format
One-to-many referencing stores an array of ObjectIds pointing to related documents.Step 2: Check each option
{ _id: 1, title: 'Post', comments: [ObjectId('abc123'), ObjectId('def456')] } uses an array of ObjectIds, which is correct. Others embed data or use a single ID incorrectly.Final Answer:
{ _id: 1, title: 'Post', comments: [ObjectId('abc123'), ObjectId('def456')] } -> Option AQuick Check:
Array of ObjectIds = correct referencing [OK]
- Embedding comment text instead of IDs
- Using a single ObjectId for many comments
- Storing comments as plain strings
posts: [{ _id: 1, title: 'Hello', comments: [101, 102] }]comments: [{ _id: 101, text: 'Nice!' }, { _id: 102, text: 'Great!' }]What will be the result of this query to find comments for post with _id 1?
db.comments.find({ _id: { $in: db.posts.findOne({ _id: 1 }).comments } })Solution
Step 1: Understand the query
The inner findOne gets the comments array [101, 102] from post _id 1.Step 2: Use $in to find matching comments
The outer find returns comments with _id in [101, 102], so both comment documents are returned.Final Answer:
[{ _id: 101, text: 'Nice!' }, { _id: 102, text: 'Great!' }] -> Option DQuick Check:
Find comments by IDs in post = matching comment docs [OK]
- Expecting post document instead of comments
- Thinking nested query causes syntax error
- Getting empty result by mistake
post document:{ _id: 1, title: 'Test', comments: ['abc', 'def'] }But when you run
db.comments.find({ _id: { $in: post.comments } }), it returns no results. What is the most likely problem?Solution
Step 1: Check data types of referenced IDs
Ifpost.commentscontains strings instead of ObjectId objects, the query won't match.Step 2: Confirm query correctness
The query syntax is correct, so the mismatch is likely due to type difference.Final Answer:
ObjectIds in post.comments are strings, not ObjectId type -> Option AQuick Check:
Type mismatch in IDs causes no matches [OK]
- Assuming empty results mean syntax error
- Ignoring data type differences
- Thinking missing field causes this error
users, posts, and comments. Each user can write many posts, and each post can have many comments. Using one-to-many referencing, which is the best way to organize references?Solution
Step 1: Understand one-to-many referencing best practice
Usually, the 'many' side stores the reference to the 'one' side to avoid large arrays.Step 2: Apply to blog system
Posts store userId (one user, many posts), comments store postId (one post, many comments), users don't store arrays.Final Answer:
posts store userId; comments store postId; users do not store references -> Option BQuick Check:
Many side stores reference to one side [OK]
- Embedding all posts or comments inside users or posts
- Storing large arrays on 'one' side documents
- Confusing which side stores the reference
Ready to prove it?
Pass the test and this pattern moves unknown
