How MongoDB indexes work (B-tree mental model) - Performance & Efficiency
When we use indexes in MongoDB, we want to find data faster. Understanding how indexes work helps us see why some searches are quick and others are slow.
We ask: How does the time to find data grow as the database gets bigger?
Analyze the time complexity of searching a MongoDB collection using a B-tree index.
// Find a document by indexed field
db.collection.find({ indexedField: value })
// The index is a B-tree structure
// It helps MongoDB quickly locate the value
This code uses an index to find documents by a specific field value efficiently.
Look at what repeats when searching the B-tree index:
- Primary operation: Checking nodes in the B-tree to find the right branch.
- How many times: The number of nodes checked grows slowly as the tree grows taller, not as the number of documents.
As the collection grows, the B-tree grows in height slowly. Searching means moving down the tree levels.
| Input Size (n) | Approx. Operations (nodes checked) |
|---|---|
| 10 | 2-3 |
| 100 | 3-4 |
| 1000 | 4-5 |
Pattern observation: The number of steps grows very slowly, much slower than the number of documents.
Time Complexity: O(log n)
This means finding a document using an index takes a small number of steps even if the database is very large.
[X] Wrong: "Searching with an index checks every document one by one."
[OK] Correct: The index uses a tree structure to jump quickly to the right place, so it does not look at every document.
Knowing how indexes speed up searches shows you understand how databases handle big data efficiently. This skill helps you explain and improve data queries in real projects.
"What if the index was a simple list instead of a B-tree? How would the time complexity change?"