MongoDB $sum
Add numeric values together.
Inside `$group`, `$sum: "$total"` adds a field across documents and `$sum: 1` counts documents. In `$set`, a single array field path can total that array’s numeric values.
Accumulators combine values from several input documents. You will use them most often inside `$group` and `$bucket` to build totals and averages.
Course use: Exercises 04, 07, 08, 09, 11, 12, and Hard Mode 13.
Example pipeline syntax { $group: { _id: "$region", revenue: { $sum: "$total" } } }
Continue learning Challenge 06: Measure each basket Add an `itemCount` field containing the total quantity across each order’s items. Challenge 14: Measure product demand Using completed orders, return `productId`, total `units`, and `revenue` for every product. Sort by revenue descending, then product ID ascending. Challenge 15: Find repeat customers For completed orders, find customers with at least two orders. Return `customerId`, `orderCount`, and `revenue`, sorted by revenue descending. Challenge 19: Rank customer lifetime leaders For completed orders, return the top three customers by revenue. Include `customerId`, `customerName`, `segment`, `revenue`, `orderCount`, and `averageOrder`. Challenge 20: Assemble an operations dashboard For completed orders, return one document with `regionalRevenue`, `largestOrders`, and `unitsByChannel`. Regional summaries need revenue and order count; largest orders need the top three compact order records; channel summaries need item units. Challenge 22: Build regional running revenue For completed orders, number each order within its region by date and calculate running regional revenue. Return `orderId`, `region`, `placedAt`, `regionalOrderNumber`, and `runningRevenue`, ordered by region and date. Challenge 24: Roll up a monthly revenue series For completed orders, calculate monthly revenue and order count. Return `month`, `revenue`, and `orderCount` in chronological order. Challenge 25: Tune a lean category report For completed web orders, report revenue by region and product category. `$match` must run first, `$project` must trim documents before `$lookup`, and the complete pipeline must use no more than nine stages. Official MongoDB $sum documentation Browse all aggregation operators