Queries that ran fast during development became noticeably slow in production once collections grew to hundreds of thousands of documents, occasionally timing out.
Analyze the actual query plan with explain(), add indexes matching real filter and sort patterns, and avoid unnecessary full collection scans.
Step-by-Step Guide
Run db.collection.find(query).explain('executionStats') to check for a COLLSCAN
Create indexes on fields used in filtering or sorting: db.collection.createIndex({ field: 1 })
For multi-field queries, build a compound index in the right order (equality, sort, range)
Avoid unanchored $regex patterns since they can't use indexes efficiently
Use projection to return only the fields actually needed instead of full documents
Switch to cursor-based pagination instead of large skip() values
Enable the profiler for slow queries: db.setProfilingLevel(1, { slowms: 100 })
Periodically review index usage since unused indexes slow down writes
Found an issue with this solution?