MongoDB — Query Performance Analysis with explain()
Diagnose slow queries using .explain("executionStats") and enable the database profiler to catch slow queries.
1Reading explain('executionStats') Output
explain() Command
db.users.find({ email: "test@example.com" }).explain("executionStats");
// Key Metrics to Check:
// 1. winningPlan.stage -> Should be "IXSCAN" (Index Scan), NOT "COLLSCAN"!
// 2. totalDocsExamined -> Should match nReturned (e.g. examined 1 doc to return 1 doc)
// 3. executionTimeMillis -> Query execution time in ms
2Enabling Database Profiler
Profiler Setup
// Log all queries taking longer than 100ms
db.setProfilingLevel(1, { slowms: 100 });
// View logged slow queries
db.system.profile.find().sort({ ts: -1 }).limit(5);