{"success":true,"name":"reach-for-the-mongodb-aggregation-pipeline-before-js-loops","description":"About to fetch many MongoDB documents to compute totals or groups in JS","category":"ai-brimind","path":"ai-brimind/reach-for-the-mongodb-aggregation-pipeline-before-js-loops/SKILL.md","file":"SKILL.md","content":"---\nname: reach-for-the-mongodb-aggregation-pipeline-before-js-loops\ndescription: \"About to fetch many MongoDB documents to compute totals or groups in JS\"\n---\n\n# Reach for the MongoDB Aggregation Pipeline Before JS Loops\n\n## When to use\nProject uses MongoDB, and you are about to loop over query results in code to sum, group, count, or join data.\n\n## Example request\nFetching all orders to sum totals in a loop → $group with $sum does it in the database, sending back one number instead of thousands of docs. Fetching two collections and matching them in JS → $lookup is the built-in join. Counting per category in a JS map → $group by category is one stage. Filtering then reshaping results in code → $match + $project keeps the work server-side. Each maps to 'the pipeline stage already exists for that computation'.\n\n## Instructions\nAct as a developer who treats pulling raw documents to compute in JS as a smell. Before writing a loop over MongoDB results: (1) name the computation in plain words (sum per group, join, count, top-N, reshape), (2) map it to pipeline stages — $match, $group, $lookup, $sort, $limit, $project, $unwind — and check whether the whole computation fits in the pipeline, because named computations almost always have a named stage, (3) order stages for efficiency: $match and $limit as early as possible so later stages process fewer documents, (4) verify the output shape with a small test run before wiring it into the app. Pull raw data into JS only when the logic genuinely cannot be expressed in stages, and state why. If the required grouping/joining rules are unclear, ask before building the pipeline. Only ship the query once the pipeline is confirmed to return the exact needed shape, and explain why the database does the heavy lifting instead of the application.\n\n## Metadata\n- role: developer\n- level: tactical\n- places: vibeCoding\n- origin: ai.brimind.pro skill #1047\n","linked_files":[],"origin":"ai.brimind.pro","owner_id":null,"source":"router"}