Introduction
Indexing Strategies in MongoDB help you decide which fields should have indexes and how those indexes should be designed for common queries. A good indexing strategy can make frequently used searches and sorting operations faster, while unnecessary indexes consume storage and add maintenance work. In this chapter, you will practice choosing useful indexes, creating compound indexes, checking query performance, and removing unnecessary indexes. MongoDB Indexing Strategies practice questions with solutions to help you understand the concepts.
Q1. Create an Index for a Frequently Searched Field
Problem Statement
The students collection is frequently searched using the email field. Create an index on email.
MongoDB Command / Query
db.students.createIndex({
email: 1
})
Expected Output
email_1
Explanation
If email is frequently used in queries, an index can help MongoDB locate matching documents more efficiently.
Q2. Index a Field Used for Sorting
Problem Statement
Students are frequently displayed according to their age in ascending order. Create an index that supports this sorting requirement.
MongoDB Command / Query
db.students.createIndex({
age: 1
})
Then run:
db.students.find().sort({
age: 1
})
Expected Output
{
name: "Aman",
age: 14
}
{
name: "Neha",
age: 15
}
{
name: "Rahul",
age: 17
}
Explanation
An index on age can support queries and sorting involving the age field.
Q3. Create a Compound Index for a Common Query
Problem Statement
The application frequently searches students by both course and age. Create a compound index for this query pattern.
MongoDB Command / Query
db.students.createIndex({
course: 1,
age: 1
})
Now query:
db.students.find({
course: "Python",
age: 17
})
Expected Output
{
name: "Rahul",
age: 17,
course: "Python"
}
Explanation
A compound index contains multiple fields. The field order matters, so the index { course: 1, age: 1 } is designed around queries that begin with course and may also use age.
Q4. Use the ESR Idea for Query Design
Problem Statement
Suppose a query filters students by course, filters age using a range, and sorts by name. Create an index following the Equality, Sort, Range (ESR) guideline.
MongoDB Command / Query
db.students.createIndex({
course: 1,
name: 1,
age: 1
})
Query:
db.students.find({
course: "Python",
age: {
$gte: 15
}
}).sort({
name: 1
})
Expected Output
{
name: "Aman",
age: 16,
course: "Python"
}
{
name: "Rahul",
age: 17,
course: "Python"
}
Explanation
The ESR guideline is a useful starting point for compound-index design:
- E = Equality fields
- S = Sort fields
- R = Range fields
The exact best index depends on the actual workload and query patterns, so explain() should be used to verify the result.
Q5. Check Whether a Query Uses an Index
Problem Statement
Check the execution plan for a query that searches students by email.
MongoDB Command / Query
First create the index:
db.students.createIndex({
email: 1
})
Then use:
db.students.find({
email: "rahul@example.com"
}).explain("executionStats")
Expected Output
A simplified execution plan may contain:
IXSCAN
Explanation
IXSCAN indicates that MongoDB used an index scan. Without a suitable index, a query may use:
COLLSCAN
The exact execution plan depends on the collection, available indexes, query, and data distribution.
Q6. Avoid Creating an Index for Every Field
Problem Statement
A collection contains these fields:
name
email
age
course
city
phone
address
The application frequently searches by email and course, but rarely searches by address. Create indexes only for the commonly used query fields.
MongoDB Command / Query
db.students.createIndex({
email: 1
})
db.students.createIndex({
course: 1
})
Expected Output
email_1
course_1
Explanation
Creating an index for every field is usually unnecessary. Indexes consume storage and can add overhead to insert, update, and delete operations.
A good strategy is to create indexes based on actual query patterns and workload.
Q7. Design an Index for Filtering and Sorting
Problem Statement
An e-commerce application frequently finds products from a specific category and sorts them by price from lowest to highest. Create a suitable compound index.
MongoDB Command / Query
db.products.createIndex({
category: 1,
price: 1
})
Query:
db.products.find({
category: "Laptop"
}).sort({
price: 1
})
Expected Output
{
name: "Basic Laptop",
category: "Laptop",
price: 45000
}
{
name: "Pro Laptop",
category: "Laptop",
price: 75000
}
Explanation
The index follows the common query pattern:
category → filter
price → sort
This can help MongoDB efficiently handle the filter and sort together.
Q8. Check an Index Before Adding Another One
Problem Statement
Before creating a new index on course, check which indexes already exist on the students collection.
MongoDB Command / Query
db.students.getIndexes()
Expected Output
[
{
name: "_id_",
key: {
_id: 1
}
},
{
name: "email_1",
key: {
email: 1
}
},
{
name: "course_1",
key: {
course: 1
}
}
]
Explanation
Checking existing indexes helps avoid unnecessary or duplicate indexes.
Q9. Remove an Unnecessary Index
Problem Statement
Suppose the course_1 index is no longer needed. Remove it from the students collection.
MongoDB Command / Query
db.students.dropIndex("course_1")
Expected Output
{
nIndexesWas: 3,
ok: 1
}
Explanation
Removing unused indexes can reduce index storage and the work MongoDB performs when documents are modified.
Important: The default
_id_index cannot be dropped.
Q10. Analyze a Query Before and After Indexing
Problem Statement
A query frequently searches employees by department and sorts them by salary. Create a suitable compound index and use explain() to inspect the query.
MongoDB Command / Query
Create the index:
db.employees.createIndex({
department: 1,
salary: 1
})
Run the query:
db.employees.find({
department: "IT"
}).sort({
salary: 1
}).explain("executionStats")
Expected Output
The execution plan may show:
IXSCAN
and execution statistics such as:
{
executionStats: {
nReturned: 3,
totalKeysExamined: 3,
totalDocsExamined: 3
}
}
Explanation
explain("executionStats") helps you understand how MongoDB executed the query.
Useful fields include:
nReturned— documents returnedtotalKeysExamined— index entries examinedtotalDocsExamined— documents examinedexecutionTimeMillis— execution time reported for the operation
The exact numbers will depend on your data and environment.
Key Takeaways
- Build indexes around real query patterns, not simply every field.
- Frequently searched fields are common candidates for indexes.
- Fields used for sorting can also benefit from appropriate indexes.
- Compound indexes can support multiple parts of a query.
- Field order matters in a compound index.
- The ESR guideline can be a useful starting point for compound-index design.
- Use
explain("executionStats")to inspect how MongoDB executes a query. IXSCANindicates an index scan, whileCOLLSCANindicates a collection scan.- Too many indexes consume storage and increase write-maintenance overhead.
- Check existing indexes with
getIndexes()before creating new ones. - Remove indexes that are no longer useful with
dropIndex(). - Index design should be based on the application’s actual workload and query patterns.
FAQs
1. What is an Indexing Strategy in MongoDB?
An indexing strategy is the process of deciding which fields to index and how to design those indexes based on the application’s common queries, filtering, sorting, and workload.
2. Should every MongoDB field have an index?
No. Creating indexes on every field is generally unnecessary. Indexes consume storage and add maintenance overhead to write operations.
3. How do I decide which fields should be indexed?
Look at the application’s frequently executed queries. Fields commonly used for filtering, sorting, joins with $lookup, or other important query patterns may be candidates for indexing.
4. What is the ESR guideline in MongoDB indexing?
ESR stands for Equality, Sort, Range. It is a guideline for arranging fields in some compound indexes. It is a useful starting point, but the actual workload and query behavior should be tested with explain().
5. Why does the order of fields matter in a compound index?
MongoDB uses the field order of a compound index to organize index entries. An index such as:
{ course: 1, age: 1 }
is generally more useful for queries beginning with course than for queries that only use age.
6. How can I check whether MongoDB is using an index?
Use explain():
db.students.find({
email: "rahul@example.com"
}).explain("executionStats")
Look at the execution plan for stages such as IXSCAN or COLLSCAN.
7. Can too many indexes affect MongoDB performance?
Yes. Indexes require storage and must be maintained when indexed documents are inserted, updated, or deleted. Therefore, indexes should be selected according to actual workload requirements.
SEO Package
SEO Title:
MongoDB Indexing Strategies Practice Questions with Solutions
Meta Description:
MongoDB Indexing Strategies Practice Questions with Solutions covering query patterns, compound indexes, ESR guidelines, explain(), sorting, and index management.
SEO Slug:mongodb-indexing-strategies-practice-questions-with-solutions
Focus Keywords:
- MongoDB Indexing Strategies Practice Questions
- MongoDB Indexing Strategies Practice Questions with Solutions
- MongoDB Indexing Strategies
- MongoDB Indexing Strategy
- MongoDB Compound Index Strategy
- MongoDB ESR Indexing
- MongoDB Explain Index Query
- MongoDB Index Optimization
Relevant Tags:
MongoDB, MongoDB Indexing Strategies, MongoDB Index Strategy, MongoDB Indexes, MongoDB Compound Index, MongoDB Single Field Index, MongoDB ESR, MongoDB Query Optimization, MongoDB explain, MongoDB IXSCAN, MongoDB COLLSCAN, MongoDB Index Performance, MongoDB Database, MongoDB Queries, MongoDB Practice Questions, MongoDB Practice Questions with Solutions, MongoDB Tutorial, MongoDB for Beginners, MongoDB Index Management
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
