{"success":true,"name":"let-mongodb-do-the-math-aggregate-in-the-database-instead-of","description":"About to fetch many records into Node.js just to count, sum, group, or rank them","category":"ai-brimind","path":"ai-brimind/let-mongodb-do-the-math-aggregate-in-the-database-instead-of/SKILL.md","file":"SKILL.md","content":"---\nname: let-mongodb-do-the-math-aggregate-in-the-database-instead-of\ndescription: \"About to fetch many records into Node.js just to count, sum, group, or rank them\"\n---\n\n# Let MongoDB Do the Math: Aggregate in the Database Instead of Fetching Everything to Compute in JS\n\n## When to use\nProject uses MongoDB/Mongoose, and you are writing code that fetches a large set of documents into the backend only to loop over them computing totals, counts per category, averages, or top-N rankings — work the database could do itself.\n\n## Example request\nDashboard fetches all payments then sums amounts in a for-loop → ships thousands of documents over the wire to produce one number; a $group aggregation returns just the number, this is what the aggregation pipeline exists for. 'Members per club' computed by loading all members and counting in JS → one $group by clubId does it in the DB, indexed and fast; fetching-to-count is the read-side cousin of the N+1 mistake. Top 10 spenders calculated by loading every user with every order → $group + $sort + $limit returns exactly ten rows; the database sorts millions better than your server sorts thousands. A computation on the 5 records ALREADY fetched for display → just compute in JS, an aggregation adds nothing; the discipline targets pulling data you would not otherwise need.\n\n## Instructions\nAct as a backend developer who respects the division of labor between the two machines in the room: the database is a purpose-built engine for filtering, grouping, and summarizing millions of rows next to where they live — and your Node.js process is a JavaScript interpreter that receives whatever survives the network. Shipping raw data to the weak machine so it can badly imitate the strong one is the mistake to catch. Whenever you notice a fetch-then-loop computing counts, sums, averages, groups, or rankings, do this: (1) Name what the code REALLY wants: not 'all the payments' but 'the total per month'; not 'all members' but 'a count per club'. That sentence — the summary, not the rows — is what should cross the network. (2) Translate it into the database's own language: MongoDB's aggregation pipeline ($match to filter first, $group for counts/sums/averages, $sort + $limit for top-N, $lookup when a join is needed) or the simple built-ins when they suffice (countDocuments, distinct). The pipeline is the named, standard tool for exactly this — hand-rolled JS reduction over a full collection fetch is the reinvented wheel here. (3) Keep your other disciplines attached, because pipelines obey the same physics: $match as EARLY as possible so the pipeline works on a filtered set, and check that the fields $match and $sort use are indexed — an unindexed aggregation scans everything just like an unindexed find. (4) Know the honest boundaries: tiny datasets already in hand → plain JS is simpler, use it; genuinely complex per-record business logic that does not map to pipeline stages → maybe the app-side loop is right, but say so explicitly after trying, not before. If the same heavy aggregation runs on every page view, remember your caching discipline — a computed summary with a stated staleness is a legitimate candidate. (5) Verify the win concretely: compare what crosses the wire before and after (thousands of documents vs a handful of result rows) and the response time at realistic data size — dev-sized collections hide this entire class of problem, so reason from production counts. Only replace the code once you can state: what summary the endpoint truly needs, which pipeline produces it, and why the network now carries answers instead of raw material — 'the loop works fine' on your 50-row dev database is precisely how these bombs get shipped.\n\n## Metadata\n- role: developer\n- level: tactical\n- places: vibeCoding\n- origin: ai.brimind.pro skill #223\n","linked_files":[],"origin":"ai.brimind.pro","owner_id":null,"source":"router"}