Sparse indexes in MongoDB - Time & Space Complexity
When using sparse indexes in MongoDB, it's important to understand how the time to find data changes as the amount of data grows.
We want to see how the index helps speed up searches and how its cost changes with more data.
Analyze the time complexity of the following MongoDB query using a sparse index.
// Create a sparse index on the field "email"
db.users.createIndex({ email: 1 }, { sparse: true })
// Query to find users with a specific email
const result = db.users.find({ email: "user@example.com" })
This code creates a sparse index on the "email" field, which only indexes documents where "email" exists. Then it queries users by email.
Look at what repeats when the query runs:
- Primary operation: The database looks up the email value in the sparse index.
- How many times: It does this once per query, but the index structure may check multiple nodes internally.
As the number of users grows, the index helps keep searches fast by skipping documents without emails.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 3-4 steps to find the email |
| 100 | About 6-7 steps |
| 1000 | About 10 steps |
Pattern observation: The number of steps grows slowly, roughly with the height of the index tree, not the total data size.
Time Complexity: O(log n)
This means the search time grows slowly as the data grows, thanks to the sparse index structure.
[X] Wrong: "Sparse indexes make the query run in constant time no matter how big the data is."
[OK] Correct: Even with sparse indexes, the database still needs to traverse the index tree, which grows slowly with data size, so it is not constant time.
Understanding how sparse indexes affect query speed shows you know how databases handle missing data efficiently, a useful skill in real projects.
"What if we changed the sparse index to a regular index? How would the time complexity change when querying documents missing the indexed field?"
Practice
sparse index in MongoDB?Solution
Step 1: Understand sparse index behavior
Sparse indexes only include documents that have the indexed field present.Step 2: Compare with other index types
Unlike regular indexes, sparse indexes skip documents missing the field, saving space and improving query speed on sparse data.Final Answer:
To index only documents that contain the indexed field -> Option AQuick Check:
Sparse index = indexes only documents with the field [OK]
- Thinking sparse indexes index all documents
- Confusing sparse indexes with backups
- Assuming sparse indexes disable indexing
email in MongoDB?Solution
Step 1: Identify sparse index syntax
The option { sparse: true } is used to create a sparse index in MongoDB.Step 2: Verify the correct command
The command db.collection.createIndex({ email: 1 }, { sparse: true }) correctly creates a sparse index on the email field.Final Answer:
db.collection.createIndex({ email: 1 }, { sparse: true }) -> Option CQuick Check:
Sparse index creation uses { sparse: true } [OK]
- Using unique instead of sparse option
- Confusing background with sparse
- Using expireAfterSeconds for sparse index
{ _id: 1, name: "Alice", age: 30 }{ _id: 2, name: "Bob" }{ _id: 3, name: "Charlie", age: 25 }and a sparse index on
age, what documents will be returned by db.collection.find({ age: { $gte: 25 } })?Solution
Step 1: Understand sparse index effect on query
The sparse index on age only indexes documents that have the age field. Document with _id 2 has no age field, so it is not indexed.Step 2: Evaluate the query filter
The query { age: { $gte: 25 } } matches documents where age is 25 or more. Documents with _id 1 (age 30) and _id 3 (age 25) match. Document _id 2 is excluded because it has no age field.Final Answer:
Documents with _id 1 and 3 only -> Option AQuick Check:
Sparse index excludes docs missing field, so only _id 1 and 3 match [OK]
- Including documents without the indexed field
- Assuming all documents are returned
- Confusing sparse index with regular index
phone field but your queries on phone are slow. What is a likely cause?Solution
Step 1: Analyze sparse index behavior
Sparse indexes only index documents with the field. If many documents lack the phone field, the index is small.Step 2: Understand query performance impact
If the index is small or not selective, MongoDB may choose not to use it, causing slower queries.Final Answer:
Many documents do not have thephonefield, so index is small and not used -> Option DQuick Check:
Sparse index small if field missing in many docs, may not speed queries [OK]
- Assuming sparse indexes always slow queries
- Forgetting to create the index
- Thinking sparse indexes index all documents
status field, but only for documents where status exists and is not null. Which MongoDB index type should you use and why?Solution
Step 1: Identify index requirement
You want to index only documents where status exists and is not null, skipping documents without status.Step 2: Match index type to requirement
Sparse indexes index only documents that have the indexed field, which fits the requirement perfectly.Final Answer:
Sparse index, because it indexes only documents with the field present -> Option BQuick Check:
Use sparse index to index only docs with the field [OK]
- Choosing regular index which indexes all documents
- Confusing TTL or unique indexes with sparse
- Not understanding sparse index skips missing fields
Ready to prove it?
Pass the test and this pattern moves unknown
