Why indexes are critical for performance in MongoDB - Performance Analysis
When we search data in MongoDB, how fast it happens depends a lot on indexes.
We want to understand how using indexes changes the work MongoDB does as data grows.
Analyze the time complexity of the following MongoDB find query with and without an index.
// Find documents where age is 30
// Without index
db.users.find({ age: 30 })
// With index on age
// Assume index created: db.users.createIndex({ age: 1 })
This code searches for users aged 30, first scanning all documents, then using an index.
Look at what repeats as data grows.
- Primary operation: Scanning documents or index entries one by one.
- How many times: Without index, it checks every document; with index, it checks fewer index entries.
As the number of users grows, the work changes like this:
| Input Size (n) | Approx. Operations Without Index | Approx. Operations With Index |
|---|---|---|
| 10 | 10 document checks | About 4 index checks |
| 100 | 100 document checks | About 7 index checks |
| 1000 | 1000 document checks | About 10 index checks |
Pattern observation: Without index, work grows directly with data size; with index, work grows slowly, like steps up a tree.
Time Complexity: O(n) without index, O(log n) with index
This means searching without an index gets slower directly with more data, but with an index, it grows much slower.
[X] Wrong: "Adding an index always makes queries instantly fast no matter what."
[OK] Correct: Indexes help most for searches on indexed fields, but if the query is on other fields or returns many results, the speed gain may be less.
Understanding how indexes change search speed shows you know how databases handle data efficiently, a key skill for real projects.
"What if we added a compound index on age and city? How would that affect the time complexity for queries filtering by both fields?"
Practice
Solution
Step 1: Understand what happens without indexes
Without indexes, MongoDB must scan every document in the collection to find matches, which is slow.Step 2: Role of indexes in query speed
Indexes allow MongoDB to quickly locate documents by using a data structure, avoiding full scans.Final Answer:
They speed up data retrieval by avoiding scanning the entire collection. -> Option AQuick Check:
Indexes improve query speed = C [OK]
- Thinking indexes backup data
- Believing indexes encrypt data
- Assuming indexes only increase storage without benefit
username in MongoDB?Solution
Step 1: Recall MongoDB index creation syntax
The correct method iscreateIndexwith a document specifying field and order (1 for ascending).Step 2: Check each option
db.collection.createIndex({username: 1}) uses correct syntax:createIndex({username: 1}). Others are invalid or incorrect method names.Final Answer:
db.collection.createIndex({username: 1}) -> Option DQuick Check:
Correct index syntax = A [OK]
- Using wrong method names like addIndex
- Passing field name as string instead of object
- Using incorrect field order values
users with an index on email, what will be the output of the following explain query?db.users.find({email: 'test@example.com'}).explain('executionStats')Which statement is true about the
executionStats output?Solution
Step 1: Understand explain with executionStats
Explain with 'executionStats' shows how MongoDB executes the query, including index usage.Step 2: Effect of index on email field
Since there is an index onemail, MongoDB uses an index scan (IXSCAN) instead of a full collection scan (COLLSCAN).Final Answer:
The query will show an IXSCAN stage indicating an index scan on email. -> Option BQuick Check:
Index present means IXSCAN used = D [OK]
- Confusing COLLSCAN with IXSCAN
- Thinking explain causes query failure
- Assuming indexes are ignored in explain
age field but your queries still perform full collection scans. What is the most likely reason?Solution
Step 1: Check index creation correctness
If the index was created with a wrong field name or syntax error, it won't be used by queries.Step 2: Eliminate other options
MongoDB supports numeric indexes, does not require restart, and indexes speed up queries, not slow them.Final Answer:
The index was created with the wrong field name or syntax error. -> Option CQuick Check:
Incorrect index creation causes no index use = B [OK]
- Believing MongoDB needs restart for indexes
- Thinking numeric fields can't be indexed
- Assuming indexes slow queries
status and createdAt. How should you design indexes to balance read speed and write performance?Solution
Step 1: Understand compound indexes for multiple query fields
A compound index on{status: 1, createdAt: -1}supports queries filtering by status and sorting by createdAt efficiently.Step 2: Balance index count for write performance
Too many indexes slow writes. Using one compound index reduces overhead while improving read speed.Final Answer:
Create a compound index on {status: 1, createdAt: -1} and avoid extra indexes. -> Option AQuick Check:
Compound index balances reads and writes = A [OK]
- Creating too many indexes hurting write speed
- Not using compound indexes for related fields
- Avoiding indexes completely hurting read speed
Ready to prove it?
Pass the test and this pattern moves unknown
