$group & Accumulators
$group & Accumulators
Section titled “$group & Accumulators”$group groups documents by a key and calculates aggregate values.
Basic Syntax
Section titled “Basic Syntax”{ $group: { _id: "$fieldToGroupBy", outputField: { $accumulator: "$valueField" } }}Common Accumulators
Section titled “Common Accumulators”| Accumulator | Meaning |
|---|---|
$sum | Adds values or counts documents |
$avg | Calculates average |
$min | Finds minimum |
$max | Finds maximum |
$push | Adds values to an array |
$addToSet | Adds unique values to an array |
$first | First value in group |
$last | Last value in group |
Count Documents Per Status
Section titled “Count Documents Per Status”db.orders.aggregate([ { $group: { _id: "$status", count: { $sum: 1 } } }])Revenue Per Customer
Section titled “Revenue Per Customer”db.orders.aggregate([ { $match: { status: "completed" } }, { $group: { _id: "$userId", totalSpent: { $sum: "$totalAmount" }, averageOrderValue: { $avg: "$totalAmount" }, orderCount: { $sum: 1 }, highestOrder: { $max: "$totalAmount" } } }, { $sort: { totalSpent: -1 } }])Group By Multiple Fields
Section titled “Group By Multiple Fields”db.orders.aggregate([ { $group: { _id: { year: { $year: "$createdAt" }, month: { $month: "$createdAt" }, status: "$status" }, count: { $sum: 1 }, revenue: { $sum: "$totalAmount" } } }])Overall Total
Section titled “Overall Total”Use _id: null when you want one result for the whole collection.
db.orders.aggregate([ { $group: { _id: null, totalRevenue: { $sum: "$totalAmount" }, totalOrders: { $sum: 1 } } }])$push vs $addToSet
Section titled “$push vs $addToSet”$push keeps duplicates:
{ $group: { _id: "$category", brands: { $push: "$brand" } } }$addToSet keeps unique values:
{ $group: { _id: "$category", brands: { $addToSet: "$brand" } } }