When not to index in MongoDB - Time & Space Complexity
Indexes help find data faster in MongoDB. But sometimes, adding an index can slow things down.
We want to understand when indexing does not improve speed and might cost more time.
Analyze the time complexity of a query without an index on a large collection.
// Find documents where status is 'active'
db.users.find({ status: 'active' })
This query searches all documents for status 'active' without an index on the status field.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Scanning each document in the collection one by one.
- How many times: Once for every document in the collection.
The query checks every document to see if it matches. More documents mean more checks.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The number of operations grows directly with the number of documents.
Time Complexity: O(n)
This means the time to run the query grows in a straight line as the collection gets bigger.
[X] Wrong: "Adding an index always makes queries faster."
[OK] Correct: Indexes take time to update when data changes and use extra space. For small collections or rarely queried fields, indexes can slow down writes and use unnecessary resources.
Understanding when not to add an index shows you know how to balance speed and cost. This skill helps you design smart databases that work well in real life.
"What if we added an index on the status field? How would the time complexity of the query change?"