MongoDB queries are slow. How do you investigate?
IntermediateTroubleshootingMongoDB
Answer
Short answer
Find the slow operations with the profiler or slow-query log, see what's running with db.currentOp(), analyse them with explain("executionStats") (look for COLLSCAN and high docs-examined-to-returned ratios), then add the right index or reshape the query. Atlas's Performance Advisor suggests indexes automatically.
Steps
// 1. What's slow? (log ops slower than 100 ms)
db.setProfilingLevel(1, { slowms: 100 })
db.system.profile.find().sort({ millis: -1 }).limit(5)
// 2. What's running right now?
db.currentOp({ secs_running: { $gte: 5 } })
db.killOp(<opid>)
// 3. Why is it slow?
db.orders.find({ status: "NEW", region: "south" }).sort({ createdAt: -1 }).explain("executionStats")
// stage: COLLSCAN, totalDocsExamined: 2,400,000, nReturned: 120 ❌
// 4. Fix
db.orders.createIndex({ status: 1, region: 1, createdAt: -1 }) // equality, equality, sort
Other causes
- Working set bigger than RAM → lots of disk reads (check WiredTiger cache metrics).
- Huge documents or unbounded arrays.
$regexwithout a prefix,$where, large$skippagination (use range-based pagination instead).- Reads on a lagging secondary.
What to say in the interview
"Profiler or slow log to find offenders, currentOp for live issues, explain executionStats to spot collection scans and poor examined-to-returned ratios, then a compound index following equality-sort-range. I also check whether the working set fits in the WiredTiger cache."