Facebook Pixel

How do I optimize a slow MongoDB query?

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.

Verify This Answer

Cross-check this information using these trusted sources:

More FAQs in How to Optimize MongoDB Queries With Indexes

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.

It skips hydrating full Mongoose documents and returns plain JS objects. Faster and uses less memory. Use for read-only queries where you only need to send JSON. Do not use it if you need to call instance methods or save the document.

Still have questions?

Browse all our FAQs or reach out to our support team

Want to upskill yourself?

Our courses are taking a Coffee break, but your curiosity shouldn't. Stay engaged with namastedev linkedin, youtube, discord and other resources while you wait.

0
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.