Covered queries with indexes in MongoDB - Time & Space Complexity
When using covered queries with indexes, we want to know how fast MongoDB can find and return data without extra work.
We ask: How does the time to get results change as the data grows?
Analyze the time complexity of the following MongoDB query using a covered index.
db.users.createIndex({ email: 1, name: 1 })
const result = db.users.find(
{ email: "user@example.com" },
{ email: 1, name: 1, _id: 0 }
)
This query uses an index on email and name to return only those fields, so MongoDB does not need to look up the full documents.
Look for repeated steps that affect speed.
- Primary operation: Searching the index tree to find matching entries.
- How many times: Once per query, as the index is searched efficiently.
The time to find a matching entry grows slowly even if the data grows a lot.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 3-4 steps to find the entry |
| 100 | About 5-6 steps |
| 1000 | About 7-8 steps |
Pattern observation: The steps grow slowly, not directly with the number of entries, because the index is like a tree that narrows down quickly.
Time Complexity: O(log n)
This means the time to find data grows slowly as the data grows, thanks to the index structure.
[X] Wrong: "Using an index means the query always takes the same time no matter how big the data is."
[OK] Correct: Even with indexes, the search takes more steps as data grows, but it grows slowly, not instantly.
Understanding how covered queries use indexes to speed up searches shows you know how databases handle data efficiently, a key skill for real projects.
What if the query requested fields not included in the index? How would the time complexity change?