How do I fix slow aggregation, pagination or N+1 queries?
Practice this questionWANT TO UNDERSTAND THE CONCEPT FIRST?Learn How do I fix slow aggregation, pagination or N+1 queries?
Definition:
Query performance depends on how much data is scanned, joined, sorted and returned for each useful result. Slow pagination and N+1 patterns often do repeated work that grows with result size. The best fix usually reduces that work before increasing hardware or connection limits.
Key points:
-
Check scan counts and indexes; reduce documents before expensive joins or groups.
-
For deep pages, use a stable cursor such as
createdAtplus_id. -
Batch related reads and reuse a bounded connection pool.
-
Keep filters, selected fields and sort keys consistent with cursor construction, including a unique tie-breaker.
Interview point:
- Compare query count, examined documents and latency before and after the change, not just endpoint code length.
Adapted from 04_MONGODB_MONGOOSE.md · “How do I fix slow aggregation, pagination or N+1 queries?”. Code examples are study fragments. Difficulty and core labels are editorial estimates; version-specific behavior should be checked against your project.