One-to-many embedding pattern in MongoDB - Time & Space Complexity
When using the one-to-many embedding pattern in MongoDB, it's important to understand how the time to run queries changes as the data grows.
We want to know how the number of embedded items affects the speed of reading or writing data.
Analyze the time complexity of the following MongoDB query that finds a document and updates an embedded array.
db.orders.updateOne(
{ _id: orderId, "items.productId": productId },
{ $inc: { "items.$.quantity": 1 } }
)
This code finds an order by its ID and increases the quantity of a specific product inside the embedded items array.
Look for repeated work inside the query.
- Primary operation: Searching through the embedded items array to find the matching product.
- How many times: The search checks each item in the array until it finds the product or reaches the end.
As the number of items in the embedded array grows, the search takes longer.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks |
| 100 | About 100 checks |
| 1000 | About 1000 checks |
Pattern observation: The time grows roughly in direct proportion to the number of embedded items.
Time Complexity: O(n)
This means the time to update grows linearly with the number of embedded items in the array.
[X] Wrong: "Updating an embedded item is always fast and constant time because it's inside one document."
[OK] Correct: The database must still scan the embedded array to find the matching item, so the time depends on the array size.
Understanding how embedded arrays affect query time helps you design better data models and explain your choices clearly in real projects.
"What if the embedded items array was indexed differently or split into separate documents? How would the time complexity change?"
Practice
one-to-many embedding pattern in MongoDB?Solution
Step 1: Understand embedding in MongoDB
Embedding means storing related data inside the main document instead of separate collections.Step 2: Identify the advantage of embedding
This approach makes reading related data faster and simpler because all data is in one place.Final Answer:
It stores related data inside the main document for faster reads. -> Option DQuick Check:
Embedding = faster reads [OK]
- Confusing embedding with referencing (separate collections)
- Thinking embedding requires joins
- Assuming embedding duplicates data
Solution
Step 1: Check the structure for embedding multiple comments
Embedding many comments requires an array of objects inside the main document.Step 2: Identify the correct JSON syntax
{ _id: 1, title: 'Post', comments: [{ user: 'Alice', text: 'Nice!' }, { user: 'Bob', text: 'Great!' }] } correctly uses an array of comment objects inside thecommentsfield.Final Answer:
{ _id: 1, title: 'Post', comments: [{ user: 'Alice', text: 'Nice!' }, { user: 'Bob', text: 'Great!' }] } -> Option CQuick Check:
Array of objects = correct embedding [OK]
- Using multiple objects without array brackets
- Storing comments as a string instead of objects
- Incorrect JSON syntax with misplaced commas or braces
posts collection:{ _id: 1, title: 'Hello', comments: [{ user: 'Alice', text: 'Hi' }, { user: 'Bob', text: 'Hello' }] }What will be the result of the query
db.posts.find({ _id: 1 }, { 'comments.user': 1, _id: 0 })?Solution
Step 1: Understand the projection in the query
The query projects only thecomments.userfield and excludes_id.Step 2: Determine the output structure
It returns thecommentsarray with only theuserfields inside each comment object.Final Answer:
{ comments: [{ user: 'Alice' }, { user: 'Bob' }] } -> Option AQuick Check:
Projection of comments.user = array of user objects [OK]
- Expecting full comment objects instead of only user fields
- Including _id when excluded in projection
- Getting array of strings instead of objects
{ _id: 1, name: 'Store', products: [{ name: 'Pen', price: 1.5 }, { name: 'Pencil', price: 1.0 }] }Which update query correctly adds a new product
{ name: 'Eraser', price: 0.5 } to the products array?Solution
Step 1: Identify the correct operator to add an object to an array
The$pushoperator adds an element to an array field.Step 2: Check the value being pushed
db.stores.updateOne({ _id: 1 }, { $push: { products: { name: 'Eraser', price: 0.5 } } }) pushes the correct object{ name: 'Eraser', price: 0.5 }into theproductsarray.Final Answer:
db.stores.updateOne({ _id: 1 }, { $push: { products: { name: 'Eraser', price: 0.5 } } }) -> Option AQuick Check:
$push with object adds to array [OK]
- Using $set replaces whole array instead of adding
- Using $addToSet with a string instead of object
- Pushing array instead of object inside array
orderId, date, and a list of items. Which schema design is best to handle up to 100 orders per user efficiently?Solution
Step 1: Understand embedding for one-to-many with moderate size
Embedding up to 100 orders inside a user document is reasonable for fast reads.Step 2: Check schema design for correct embedding
{ _id: userId, name: 'User', orders: [{ orderId, date, items: [{ productId, qty }] }] } embeds an array of order objects, each with its own items array, which fits the one-to-many embedding pattern well.Final Answer:
{ _id: userId, name: 'User', orders: [{ orderId, date, items: [{ productId, qty }] }] } -> Option BQuick Check:
Embed array of orders with nested items for one-to-many [OK]
- Using object instead of array for multiple orders
- Separating orders into another collection unnecessarily
- Storing only order IDs without details inside user
Ready to prove it?
Pass the test and this pattern moves unknown
