Why document design matters in MongoDB - Performance Analysis
When working with MongoDB, how you design your documents affects how fast queries run.
We want to see how the shape of data changes the work the database does.
Analyze the time complexity of the following MongoDB query on different document designs.
// Find all orders for a customer
db.orders.find({ customerId: 123 })
This query looks up orders by customer ID. Document design affects how many documents and fields are scanned.
Look at what repeats when the query runs.
- Primary operation: Scanning documents to find matching customerId.
- How many times: Once for each order document in the collection.
As the number of orders grows, the database checks more documents.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 document checks |
| 100 | 100 document checks |
| 1000 | 1000 document checks |
Pattern observation: More orders mean more documents to scan, so work grows linearly.
Time Complexity: O(n)
This means the time to find orders grows directly with how many orders exist.
[X] Wrong: "Adding more fields to documents won't affect query speed."
[OK] Correct: Larger documents take longer to read and transfer, slowing queries even if the fields aren't used.
Understanding how document design affects query speed shows you think about real data and user needs, a key skill in database work.
"What if we added an index on customerId? How would the time complexity change?"