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?"