0
0
MongoDBquery~5 mins

When not to index in MongoDB - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: When not to index
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

The query checks every document to see if it matches. More documents mean more checks.

Input Size (n)Approx. Operations
1010 checks
100100 checks
10001000 checks

Pattern observation: The number of operations grows directly with the number of documents.

Final Time Complexity

Time Complexity: O(n)

This means the time to run the query grows in a straight line as the collection gets bigger.

Common Mistake

[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.

Interview Connect

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.

Self-Check

"What if we added an index on the status field? How would the time complexity of the query change?"