MongoDB Query to Find Total Per Group Using Aggregation
$group stage to find totals per group, for example: db.collection.aggregate([{ $group: { _id: "$groupField", total: { $sum: "$valueField" } } }]).Examples
How to Think About It
$group and then summing the values of another field within each group using $sum. This aggregates data by categories or types, similar to summing expenses by month in a spreadsheet.Algorithm
Code
db.collection.aggregate([
{ $group: { _id: "$category", total: { $sum: "$quantity" } } }
])Dry Run
Let's trace the aggregation on example documents grouped by 'category' and summed by 'quantity'.
Group documents by category
Documents: [{category: 'fruit', quantity: 10}, {category: 'vegetable', quantity: 5}, {category: 'fruit', quantity: 15}]
Sum quantity values per group
fruit: 10 + 15 = 25, vegetable: 5
Return grouped totals
[{_id: 'fruit', total: 25}, {_id: 'vegetable', total: 5}]
| Category | Quantity | Running Total |
|---|---|---|
| fruit | 10 | 10 |
| vegetable | 5 | 5 |
| fruit | 15 | 25 |
Why This Works
Step 1: Grouping documents
The $group stage groups documents by the specified field, here category, creating buckets for each unique value.
Step 2: Summing values
Within each group, $sum adds up the values of the quantity field to get the total per group.
Step 3: Output format
The result documents have _id as the group key and total as the sum, showing totals per group.
Alternative Approaches
db.collection.aggregate([
{ $group: { _id: "$category", uniqueQuantities: { $addToSet: "$quantity" } } }
])db.collection.mapReduce( function() { emit(this.category, this.quantity); }, function(key, values) { return Array.sum(values); }, { out: "totals_per_category" } )
Complexity: O(n) time, O(k) space
Time Complexity
The aggregation scans all n documents once, grouping them by k unique keys, so time is O(n).
Space Complexity
Space depends on the number of groups k, as it stores totals per group, so O(k).
Which Approach is Fastest?
The aggregation pipeline with $group is faster and more efficient than map-reduce for this task.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Aggregation with $group | O(n) | O(k) | Fast grouping and summing |
| Map-Reduce | O(n) | O(k) | Complex custom aggregation, slower |
| $group with $addToSet | O(n) | O(k) | Unique value collection, not sum |
$group and $sum for efficient grouping and totaling in MongoDB.$group expressions causes errors or wrong results.