Problem Statement
What is the explain() method in MongoDB and what key metrics should you look for when analyzing query performance?
Explanation
The explain method shows how MongoDB executes a query, including which indexes are used, how many documents are scanned, and the execution time. This is crucial for query optimization and identifying performance bottlenecks.
You can use different verbosity modes: queryPlanner shows the winning plan, executionStats shows detailed execution statistics, and allPlansExecution shows all considered plans.
Key metrics to analyze include: totalDocsExamined which shows how many documents MongoDB scanned, totalDocsReturned which shows how many documents matched your query, executionTimeMillis which shows the query execution time in milliseconds, and indexName which tells you if an index was used.
Ideally, totalDocsExamined should be close to totalDocsReturned. If MongoDB scans many more documents than it returns, you need better indexes. A query is efficient when it examines only the documents that match your criteria.
Code Solution
SolutionRead Only
// Basic explain
db.users.find({ age: 30 }).explain()
// Execution statistics mode
db.users.find({ age: 30 }).explain("executionStats")
// Key output:
{
executionStats: {
executionTimeMillis: 2,
totalDocsExamined: 1,
totalDocsReturned: 1,
executionStages: {
stage: "IXSCAN", // Index scan
indexName: "age_1"
}
}
}Practice Sets
This question appears in the following practice sets:
