{"success":true,"name":"run-explain-before-blaming-or-fixing-a-slow-mongodb-query","description":"A MongoDB query is slow and you are about to try a fix","category":"ai-brimind","path":"ai-brimind/run-explain-before-blaming-or-fixing-a-slow-mongodb-query/SKILL.md","file":"SKILL.md","content":"---\nname: run-explain-before-blaming-or-fixing-a-slow-mongodb-query\ndescription: \"A MongoDB query is slow and you are about to try a fix\"\n---\n\n# Run explain() Before Blaming or Fixing a Slow MongoDB Query\n\n## When to use\nProject uses MongoDB, and a query/aggregation is slow and you have not yet read its execution plan.\n\n## Example request\n'It's slow, add an index' → explain() shows an existing index IS used but 500k docs match; the filter, not the index, is the problem. Slow aggregation → explain shows $match runs after $lookup; reordering stages fixes it without new indexes. Query fast locally, slow in prod → local has 100 docs; explain on prod data reveals the COLLSCAN. Adding an index that explain later shows unused → the sort order or field order didn't match; ESR order was violated. Each maps to 'the plan is the evidence; fixes without it are guesses'.\n\n## Instructions\nAct as a diagnostician who refuses to optimize a MongoDB query before reading its execution plan. When a query is slow: (1) run .explain('executionStats') on the exact query the app runs (same filter, sort, projection — not a simplified version), (2) read the evidence: stage type (COLLSCAN vs IXSCAN), totalKeysExamined, totalDocsExamined vs nReturned — a big examined-to-returned ratio is the smoking gun, (3) state a hypothesis from the plan ('no index on the sort field', 'index exists but field order breaks ESR', '$match placed too late in the pipeline'), (4) apply ONE fix matching the hypothesis, re-run explain, and compare numbers. Never stack multiple fixes blind. If you cannot run explain on realistic data volume, say so — 100 local docs prove nothing. Only declare the query fixed once the new plan shows the improvement in numbers, and explain the root cause the plan revealed, not just that 'it feels faster now'.\n\n## Metadata\n- role: developer\n- level: tactical\n- places: vibeCoding\n- origin: ai.brimind.pro skill #1052\n","linked_files":[],"origin":"ai.brimind.pro","owner_id":null,"source":"router"}