0
0
MongoDBquery~5 mins

createIndex method in MongoDB - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: createIndex method
O(n)
Understanding Time Complexity

When we create an index in MongoDB, the database builds a structure to help find data faster later.

We want to know how the time to build this index changes as the amount of data grows.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


db.collection.createIndex({ fieldName: 1 })
    

This code creates an ascending index on the field named "fieldName" in the collection.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Scanning all documents in the collection to read the indexed field.
  • How many times: Once for each document in the collection.
How Execution Grows With Input

Explain the growth pattern intuitively.

Input Size (n)Approx. Operations
10About 10 document reads and index entries
100About 100 document reads and index entries
1000About 1000 document reads and index entries

Pattern observation: The time grows roughly in direct proportion to the number of documents.

Final Time Complexity

Time Complexity: O(n)

This means the time to create the index grows linearly with the number of documents in the collection.

Common Mistake

[X] Wrong: "Creating an index is instant no matter how big the collection is."

[OK] Correct: The database must look at every document to build the index, so more documents mean more work and more time.

Interview Connect

Understanding how index creation time grows helps you explain database performance and design choices clearly in real projects.

Self-Check

"What if we created a compound index on two fields instead of one? How would the time complexity change?"