Introduction
MongoDB’s explain() method helps developers understand how MongoDB executes a query. It can show whether MongoDB uses an index, scans the entire collection, how many documents or index keys it examines, and other execution details. In this chapter, you will practice using explain(), understanding IXSCAN and COLLSCAN, checking execution statistics, and comparing queries with different indexes. MongoDB explain() practice questions with solutions to help you understand the concepts.
Q1. Use explain() with a Basic Query
Problem Statement
Display the execution plan for a query that finds a student named Rahul.
MongoDB Command / Query
db.students.find({
name: "Rahul"
}).explain()
Expected Output
The output contains an execution plan similar to:
{
queryPlanner: {
...
}
}
Explanation
explain() does not simply return the matching documents. Instead, it provides information about how MongoDB plans and executes the query.
Q2. Use explain("executionStats")
Problem Statement
Find students whose age is greater than 15 and display detailed execution statistics.
MongoDB Command / Query
db.students.find({
age: {
$gt: 15
}
}).explain("executionStats")
Expected Output
The result contains information similar to:
{
executionStats: {
executionSuccess: true,
nReturned: 3,
executionTimeMillis: 1,
totalKeysExamined: 0,
totalDocsExamined: 10
}
}
Explanation
"executionStats" provides actual execution information, including:
nReturned— number of documents returnedtotalKeysExamined— number of index entries examinedtotalDocsExamined— number of documents examinedexecutionTimeMillis— reported execution time
The exact values depend on your data and indexes.
Q3. Check for a Collection Scan
Problem Statement
Check how MongoDB executes a query searching for students from Delhi.
MongoDB Command / Query
db.students.find({
city: "Delhi"
}).explain("executionStats")
Expected Output
If there is no suitable index, the execution plan may contain:
COLLSCAN
Explanation
COLLSCAN means Collection Scan.
MongoDB examines documents in the collection to find matching documents.
For a small collection, this may be perfectly acceptable. For a large collection, an appropriate index may reduce the amount of data MongoDB needs to examine.
Q4. Create an Index and Check for IXSCAN
Problem Statement
Create an index on city and check the execution plan for a query searching for students from Delhi.
MongoDB Command / Query
Create the index:
db.students.createIndex({
city: 1
})
Run the query:
db.students.find({
city: "Delhi"
}).explain("executionStats")
Expected Output
The execution plan may contain:
IXSCAN
Explanation
IXSCAN means Index Scan.
MongoDB is using an index to locate matching records rather than scanning the entire collection.
Q5. Check How Many Documents Were Examined
Problem Statement
Find students enrolled in Python and check how many documents MongoDB examined.
MongoDB Command / Query
db.students.find({
course: "Python"
}).explain("executionStats")
Look for:
executionStats.totalDocsExamined
Expected Output
Example:
totalDocsExamined: 5
Explanation
totalDocsExamined tells you how many documents MongoDB examined during execution.
The actual number depends on your collection, indexes, query, and query plan.
Q6. Check How Many Index Keys Were Examined
Problem Statement
Create an index on email and inspect how many index keys MongoDB examines when searching for an email address.
MongoDB Command / Query
Create the index:
db.students.createIndex({
email: 1
})
Run:
db.students.find({
email: "rahul@example.com"
}).explain("executionStats")
Look for:
executionStats.totalKeysExamined
Expected Output
Example:
totalKeysExamined: 1
Explanation
totalKeysExamined shows how many index entries MongoDB examined during query execution.
The exact value can vary depending on the query and index.
Q7. Check the Number of Returned Documents
Problem Statement
Find students older than 15 and use explain() to determine how many documents the query returned.
MongoDB Command / Query
db.students.find({
age: {
$gt: 15
}
}).explain("executionStats")
Look for:
executionStats.nReturned
Expected Output
Example:
nReturned: 4
Explanation
nReturned represents the number of documents returned by the query.
It is different from totalDocsExamined.
For example:
nReturned: 4
totalDocsExamined: 10
means MongoDB returned 4 documents after examining 10 documents.
Q8. Analyze a Sorted Query with explain()
Problem Statement
Create an index on age and check the execution plan for a query that sorts students by age.
MongoDB Command / Query
Create the index:
db.students.createIndex({
age: 1
})
Run:
db.students.find()
.sort({
age: 1
})
.explain("executionStats")
Expected Output
The execution plan may contain an index-related stage such as:
IXSCAN
Explanation
An appropriate index can help MongoDB with both finding data and supporting certain sort operations.
The exact winning plan depends on the query, collection size, available indexes, and data distribution.
Q9. Analyze a Compound Index Query
Problem Statement
Create a compound index on course and age, then use explain() to analyze a query that filters using both fields.
MongoDB Command / Query
Create the index:
db.students.createIndex({
course: 1,
age: 1
})
Run:
db.students.find({
course: "Python",
age: {
$gte: 16
}
}).explain("executionStats")
Expected Output
The execution plan may contain:
IXSCAN
and execution statistics such as:
{
nReturned: 2,
totalKeysExamined: 2,
totalDocsExamined: 2
}
Explanation
A compound index can support queries involving multiple fields when its field order matches the query pattern.
The numbers above are examples. Your actual statistics will depend on your collection.
Q10. Compare Query Plans Before and After Indexing
Problem Statement
Check the execution plan for an email query, create an index on email, and check the execution plan again.
MongoDB Command / Query
First, run:
db.students.find({
email: "rahul@example.com"
}).explain("executionStats")
If no suitable index exists, the plan may contain:
COLLSCAN
Now create an index:
db.students.createIndex({
email: 1
})
Run the query again:
db.students.find({
email: "rahul@example.com"
}).explain("executionStats")
Expected Output
Before indexing, the plan may contain:
COLLSCAN
After indexing, the plan may contain:
IXSCAN
Explanation
This is a practical way to investigate how an index changes query execution.
However, IXSCAN by itself does not automatically mean a query is faster in every situation. MongoDB’s optimizer considers the available plans and workload. Use execution statistics and real workload measurements when evaluating index changes.
Key Takeaways
explain()shows how MongoDB plans or executes a query.explain()can be used withfind(), sorting, and other query operations.explain("executionStats")provides actual execution statistics.COLLSCANmeans MongoDB performed a collection scan.IXSCANmeans MongoDB used an index scan.nReturnedshows how many documents were returned.totalDocsExaminedshows how many documents were examined.totalKeysExaminedshows how many index entries were examined.executionTimeMillisreports execution time for the examined operation.- Creating an index can change a query plan from a collection scan to an index-based plan, depending on the query and data.
IXSCANalone should not be treated as a guarantee of better performance.- Always consider actual query patterns, data size, and workload when analyzing indexes.
FAQs
1. What is explain() in MongoDB?
explain() is a MongoDB method used to inspect how MongoDB plans and executes a query.
2. What does explain("executionStats") do?
It provides detailed information about the execution of the query, including returned documents, examined documents, examined index keys, and reported execution time.
3. What does COLLSCAN mean in MongoDB?
COLLSCAN means Collection Scan. MongoDB examines documents in the collection to find matching records.
4. What does IXSCAN mean in MongoDB?
IXSCAN means Index Scan. MongoDB is scanning an index to help execute the query.
5. What is totalDocsExamined?
totalDocsExamined indicates the number of documents MongoDB examined while executing the query.
6. What is totalKeysExamined?
totalKeysExamined indicates the number of index entries MongoDB examined during query execution.
7. Does IXSCAN always mean the query is faster?
No. IXSCAN only tells you that an index scan was used. Query performance depends on factors such as data size, selectivity, index design, query shape, sorting, and the overall workload.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
