createIndex method in MongoDB - Time & Space 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.
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 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.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 document reads and index entries |
| 100 | About 100 document reads and index entries |
| 1000 | About 1000 document reads and index entries |
Pattern observation: The time grows roughly in direct proportion to the number of documents.
Time Complexity: O(n)
This means the time to create the index grows linearly with the number of documents in the collection.
[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.
Understanding how index creation time grows helps you explain database performance and design choices clearly in real projects.
"What if we created a compound index on two fields instead of one? How would the time complexity change?"