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

1

Run db.collection.find(query).explain('executionStats') to check for a COLLSCAN

2

Create indexes on fields used in filtering or sorting: db.collection.createIndex({ field: 1 })

3

For multi-field queries, build a compound index in the right order (equality, sort, range)

4

Avoid unanchored $regex patterns since they can't use indexes efficiently

5

Use projection to return only the fields actually needed instead of full documents

6

Switch to cursor-based pagination instead of large skip() values

7

Enable the profiler for slow queries: db.setProfilingLevel(1, { slowms: 100 })

8

Periodically review index usage since unused indexes slow down writes

Found an issue with this solution?

Related Topics

mongodb compound index ordercursor based paginationmongodb profiler slow queries