Beginner LevelMongoDB & Mongoose
How do you analyze MongoDB queries using explain("executionStats")?
❓ Interview Prompt: Explain query execution profiling via explain("executionStats"), analyzing COLLSCAN vs IXSCAN, totalKeysExamined, and totalDocsExamined.
Calling 'explain("executionStats")' returns diagnostic metrics revealing how MongoDB's Query Planner executed a query:
Critical Execution Metrics:
•
stage: 'IXSCAN' (Used B-Tree Index - Fast!) vs 'COLLSCAN' (Scanned Entire Collection - Slow!).
•
totalKeysExamined: Number of index entries scanned.
•
totalDocsExamined: Number of underlying collection documents read.
Goal: Keep 'totalDocsExamined' as close to 'nReturned' as possible!
Code Implementation Example
typescript
import { OrderModel } from './models/Order';
async function profileOrderQuery() {
const explainResult = await OrderModel.find({
status: 'PENDING',
totalAmount: { $gte: 50 }
}).explain('executionStats');
console.log('Winning Plan Stage:', explainResult.executionStats.executionStages.stage);
console.log('Docs Examined:', explainResult.executionStats.totalDocsExamined);
}💡Analyzing query execution plans using explain('executionStats').
🎯 Interview Key Takeaway
Use explain('executionStats') to verify queries execute via IXSCAN rather than unindexed COLLSCAN.
#explain#executionStats#IXSCAN#COLLSCAN#Beginner
Back to all MongoDB & Mongoose Questions→