Analyze MongoDB Query Performance with Explain Plan
📖 Scenario: You are managing a small online bookstore database in MongoDB. You want to understand how MongoDB runs your search queries to make them faster.
🎯 Goal: Learn how to use MongoDB's explain() method to see the queryPlanner and executionStats for a query. This helps you understand how MongoDB finds data and how efficient the query is.
📋 What You'll Learn
Create a collection called books with sample book documents
Write a query to find books by a specific author
Use explain('executionStats') on the query to get detailed info
Access and understand the queryPlanner and executionStats parts of the explain output
💡 Why This Matters
🌍 Real World
Understanding explain plans helps database administrators and developers optimize queries for faster data retrieval in real applications like online stores or content management systems.
💼 Career
Knowing how to analyze query plans is a key skill for roles like database administrator, backend developer, and data engineer to improve application performance.
Progress0 / 4 steps
1
Create the books collection with sample data
Create a MongoDB collection called books and insert these exact documents: { title: 'The Hobbit', author: 'J.R.R. Tolkien', year: 1937 }, { title: '1984', author: 'George Orwell', year: 1949 }, and { title: 'Animal Farm', author: 'George Orwell', year: 1945 }.
MongoDB
Hint
Use db.books.insertMany() with an array of objects for the books.
2
Write a query to find books by George Orwell
Write a MongoDB query called query that finds all books where the author is exactly 'George Orwell'.
MongoDB
Hint
Define a variable query with the filter { author: 'George Orwell' }.
3
Use explain('executionStats') to analyze the query
Use db.books.find(query).explain('executionStats') and save the result in a variable called explainResult.
MongoDB
Hint
Use explain('executionStats') on the find query and assign it to explainResult.
4
Access queryPlanner and executionStats from the explain result
Create two variables: planner to hold explainResult.queryPlanner and stats to hold explainResult.executionStats.
MongoDB
Hint
Assign explainResult.queryPlanner to planner and explainResult.executionStats to stats.
Practice
(1/5)
1. What does the queryPlanner section in MongoDB's explain output show?
easy
A. The plan MongoDB chooses to execute the query
B. The total time taken to run the query
C. The number of documents returned by the query
D. The syntax errors in the query
Solution
Step 1: Understand the role of queryPlanner
The queryPlanner shows the strategy MongoDB picks to run the query, like which indexes it uses.
Step 2: Differentiate from executionStats
executionStats shows runtime details, not the plan itself.
Final Answer:
The plan MongoDB chooses to execute the query -> Option A
Quick Check:
queryPlanner = plan chosen [OK]
Hint: queryPlanner shows the plan, executionStats shows runtime [OK]
Common Mistakes:
Confusing queryPlanner with executionStats
Thinking queryPlanner shows query results
Assuming queryPlanner shows errors
2. Which of the following is the correct way to get execution stats for a query in MongoDB?
easy
A. db.collection.find({}).explain('runStats')
B. db.collection.find({}).explain('queryPlan')
C. db.collection.find({}).explain('statsExecution')
D. db.collection.find({}).explain('executionStats')
Solution
Step 1: Recall the correct explain verbosity
MongoDB uses 'executionStats' to show runtime details.
Step 2: Check option syntax
Only db.collection.find({}).explain('executionStats') uses the correct string 'executionStats' with explain().
Final Answer:
db.collection.find({}).explain('executionStats') -> Option D
Quick Check:
Use 'executionStats' for runtime info [OK]
Hint: Use 'executionStats' string inside explain() for runtime stats [OK]
Common Mistakes:
Using wrong strings like 'queryPlan' or 'runStats'
This value shows how many documents MongoDB looked at to find matching results.
Step 2: Differentiate from nReturned
nReturned is how many documents matched and were returned, not scanned.
Final Answer:
Number of documents scanned to find matches -> Option B
Quick Check:
totalDocsExamined = docs scanned [OK]
Hint: totalDocsExamined counts scanned docs, not returned [OK]
Common Mistakes:
Confusing scanned docs with returned docs
Thinking it counts indexes used
Assuming it is total collection size
4. You run db.users.find({age: 30}).explain('executionStat') but get an error. Which is the likely cause?
medium
A. The verbosity string 'executionStats' is misspelled
B. Explain does not support 'executionStats' verbosity
C. The query filter syntax is invalid
D. The collection name is incorrect
Solution
Step 1: Check common explain errors
Misspelling the verbosity string causes errors because MongoDB expects exact strings.
Step 2: Validate other options
Collection name and query syntax are valid; 'executionStats' is supported.
Final Answer:
The verbosity string 'executionStats' is misspelled -> Option A
Quick Check:
Correct spelling of verbosity string is required [OK]
Hint: Check spelling of verbosity string in explain() [OK]
Common Mistakes:
Misspelling 'executionStats' as 'executionStat'
Assuming explain() doesn't support 'executionStats'
Blaming query syntax without checking verbosity
5. You want to optimize a query that scans 1000 documents but returns only 2. The explain output shows totalDocsExamined: 1000 and nReturned: 2. What is the best next step?
hard
A. Rewrite the query to return all documents in the collection
B. Increase the batch size to return more documents faster
C. Add an index on the query fields to reduce scanned documents
D. Ignore the explain output; it does not affect performance
Solution
Step 1: Analyze the explain stats
High totalDocsExamined but low nReturned means many documents scanned unnecessarily.
Step 2: Choose optimization strategy
Adding an index on query fields helps MongoDB scan fewer documents and improve speed.
Final Answer:
Add an index on the query fields to reduce scanned documents -> Option C
Quick Check:
Index reduces scanned docs, improves query [OK]
Hint: High scanned vs returned? Add index on query fields [OK]
Common Mistakes:
Ignoring explain output and performance impact
Increasing batch size without fixing scan issue
Trying to return all documents unnecessarily
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.