Query OptimizationAdvanced
1Question 1 of 1
javascriptHow do you optimize slow queries in MongoDB using explain('executionStats')?
Explanation & Concept
Calling `.explain('executionStats')` on a query returns internal execution engine metrics.
Key metrics to evaluate: • `totalDocsExamined` vs `nReturned`: If `totalDocsExamined` is much higher than `nReturned`, the query is performing unindexed scans. • `stage`: `COLLSCAN` means a full collection scan (bad); `IXSCAN` indicates an index scan (good). • `executionTimeMillis`: Actual runtime taken to satisfy the query.
Code Example
javascript
db.users.find({ "location.city": "Austin", status: "ACTIVE" })
.sort({ createdAt: -1 })
.explain("executionStats");
// Look for:
// executionStats: {
// nReturned: 15,
// totalDocsExamined: 15, // Perfect 1:1 ratio!
// totalKeysExamined: 15,
// executionTimeMillis: 2
// }How It Works & Key Takeaways
When `totalDocsExamined` matches `nReturned` exactly, every document retrieved from disk met the search criteria, proving the index cleanly isolated the result set.
Mock Test · 1 Questions · Optional
Ready for Change Streams?
Take a quick test to evaluate yourself, or move straight to the next module.
Advanced1 questions