How do I fix N+1 queries in MongoDB?
Use populate. Instead of looping over documents and calling findById for each reference, use Model.find().populate('refField'). Mongoose does it in 2 queries (one for the parent, one for all referenced docs).
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in Common MongoDB Performance Mistakes (and How to Fix Them)
No indexes on hot queries, skip for large offsets, returning all fields, N+1 queries, unbounded arrays, $where and unindexed $regex, no compound indexes, indexing every field, countDocuments on large collections, hydrating full documents, no connection pooling, and sync calls.
MongoDB still scans the skipped documents before returning the ones you want. For offset 100000, it scans 100000 docs. Use cursor-based pagination instead: find documents where createdAt is less than the last cursor.
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
