{"success":true,"name":"back-every-mongodb-sort-with-an-index-or-a-small-result-set","description":"Adding a sort to a MongoDB query on a growing collection","category":"ai-brimind","path":"ai-brimind/back-every-mongodb-sort-with-an-index-or-a-small-result-set/SKILL.md","file":"SKILL.md","content":"---\nname: back-every-mongodb-sort-with-an-index-or-a-small-result-set\ndescription: \"Adding a sort to a MongoDB query on a growing collection\"\n---\n\n# Back Every MongoDB Sort With an Index or a Small Result Set\n\n## When to use\nProject uses MongoDB, and a find or aggregation sorts results by a field on a collection that will grow.\n\n## Example request\nsort({ createdAt: -1 }) with no index on createdAt → MongoDB sorts in memory; past the 100MB limit the query errors outright. Sort works for months then starts failing → the collection grew into the in-memory sort limit; the bug was latent from day one. $sort late in an aggregation on big intermediate data → move $sort next to $match where an index can serve it, or add $limit. Sorting a filtered handful of docs → in-memory sort on 20 documents is fine; the rule is about unbounded sets. Each maps to 'an unindexed sort is a time bomb sized to your growth'.\n\n## Instructions\nAct as a developer who treats every .sort() as a claim that must be backed by either an index or a provably small result set. When adding sorted queries on MongoDB: (1) check whether an index covers the sort — same field(s), compatible direction — remembering compound rules: the index must serve filter and sort together following ESR order (equality fields, then sort fields, then ranges), (2) if no index serves it, decide: add the index, or prove the sorted set is small and bounded (a filter guaranteeing few docs) — 'small today' does not count, growth is the whole question, (3) know the failure you're preventing: unindexed sorts happen in memory with a hard limit (~100MB), so the query that works now will start throwing errors at scale, silently scheduled by your growth curve, (4) in aggregations, position $sort where the index can serve it (right after the initial $match) or bound it with $limit, and verify with explain() that the plan shows an index-backed sort, not an in-memory SORT stage. If growth expectations are unknown, ask. Only ship the sorted query once explain confirms its backing, and explain why the sort survives the collection's future size, not just its current one.\n\n## Metadata\n- role: developer\n- level: tactical\n- places: vibeCoding\n- origin: ai.brimind.pro skill #1153\n","linked_files":[],"origin":"ai.brimind.pro","owner_id":null,"source":"router"}