Introduction
The $sum accumulator helps add up numbers in a group. It is useful to find totals easily.
The $sum accumulator helps add up numbers in a group. It is useful to find totals easily.
{ $group: { _id: <grouping_key>, total: { $sum: <expression> } } }The $sum can add values from a field or count documents if used with 1.
The _id defines how documents are grouped before summing.
{ $group: { _id: "$category", totalSales: { $sum: "$amount" } } }{ $group: { _id: "$status", count: { $sum: 1 } } }This query groups sales by item name and sums the quantity sold for each item.
db.sales.aggregate([
{ $group: { _id: "$item", totalQuantity: { $sum: "$quantity" } } }
])If the field used in $sum is missing or null in a document, it counts as zero.
You can use $sum inside $group or $project stages depending on your need.
$sum adds numbers or counts documents in groups.
Use it inside $group to get totals per group.
It helps quickly find totals like sales, counts, or points.
$sum accumulator do in a MongoDB aggregation pipeline?$sum$sum accumulator adds numeric values or counts documents when used in a $group stage.$avg which calculates averages, $sum only totals values or counts documents.$sum = Adds or counts [OK]price in a $group stage?$sum, not sum, and the value must be a string with "$" prefix.{ "category": "A", "value": 10 }{ "category": "A", "value": 20 }{ "category": "B", "value": 5 }[{ $group: { _id: "$category", totalValue: { $sum: "$value" } } }][{ $group: { _id: "$type", total: { $sum: value } } }]store and amount. You want to find the total sales per store but only for stores with total sales above 1000. Which aggregation pipeline correctly uses $sum and filters the results?Pass the test and this pattern moves unknown