Problem Statement
What strategies can you use to optimize slow MongoDB queries?
Explanation
First, use the explain method with executionStats to identify bottlenecks. Look at totalDocsExamined versus totalDocsReturned. If MongoDB scans many more documents than it returns, you need better indexes.
Second, create appropriate indexes based on your query patterns. Index the fields you filter, sort, or use in projections. For queries with multiple conditions, consider compound indexes with the most selective fields first.
Third, use projections to return only the fields you need, reducing network transfer and memory usage. Fourth, avoid queries that cannot use indexes efficiently, such as negation operators like dollar ne or regular expressions without anchors.
Fifth, for complex queries, restructure them or use the aggregation pipeline with early filtering stages. Sixth, ensure your indexes fit in RAM for best performance. Finally, consider using covered queries where all queried fields are in the index, allowing MongoDB to return results entirely from the index without examining documents.
Code Solution
SolutionRead Only
// Check query performance
db.users.find({ age: { $gt: 25 } }).explain("executionStats")
// Optimize with index
db.users.createIndex({ age: 1 })
// Use projection to reduce data transfer
db.users.find(
{ age: { $gt: 25 } },
{ name: 1, email: 1, _id: 0 }
)
// Covered query (all fields in index)
db.users.createIndex({ age: 1, name: 1 })
db.users.find(
{ age: 30 },
{ name: 1, _id: 0 }
)Practice Sets
This question appears in the following practice sets:
