Anti-patterns to avoid in MongoDB - Time & Space Complexity
When working with MongoDB, some ways of writing queries or structuring data can slow things down a lot as your data grows.
We want to see which common mistakes cause the database to do much more work than needed.
Analyze the time complexity of this MongoDB query pattern.
// Find documents without an index on 'status'
db.orders.find({ status: "pending" })
// Update many documents without a filter on indexed field
db.orders.updateMany({}, { $set: { processed: true } })
// Using $where with JavaScript function
db.orders.find({ $where: function() { return this.amount > 100; } })
This code shows common query patterns that can cause slow performance as data grows.
Look for operations that repeat over many documents.
- Primary operation: Scanning documents one by one because no index is used.
- How many times: Once for each document in the collection.
As the number of documents grows, the database must check each one without shortcuts.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 document checks |
| 100 | 100 document checks |
| 1000 | 1000 document checks |
Pattern observation: The work grows directly with the number of documents, so doubling data doubles work.
Time Complexity: O(n)
This means the database must look at every document, so more data means more work in a straight line.
[X] Wrong: "Using $where or no index is fine because MongoDB is fast enough to handle it."
[OK] Correct: Without indexes, MongoDB must scan every document, which gets slower as data grows and can cause delays.
Understanding these anti-patterns helps you write queries that stay fast even when data grows big, a skill valuable in real projects.
"What if we added an index on the 'status' field? How would the time complexity change?"