Why avoid $where and unindexed $regex?
$where runs JavaScript in the database (slow). $regex on an unindexed field scans the whole collection. Use a text index for search, or index the field if you need regex. Both operators are common causes of slow queries.
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in How to Optimize MongoDB Queries With Indexes
Run explain('executionStats'). If totalDocsExamined equals the collection size, add an index for the query fields. Use compound indexes for multi-field queries. Use .lean() and select only needed fields. Paginate with cursor instead of skip.
Look at executionStats.totalDocsExamined (should be small), executionStats.totalKeysExamined (should be small), and winningPlan.stage (COLLSCAN is bad, IXSCAN is good). If totalDocsExamined equals the collection size, the index is not used.
MongoDB still scans the skipped documents before returning the ones you want. For large offsets, use cursor-based pagination: find documents where createdAt is less than the last cursor. Faster because MongoDB uses an index.
Still have questions?
Browse all our FAQs or reach out to our support team
