MongoDB $group
Combine documents that share a key into summary documents.
The `_id` expression defines the group. Every other output field must use an accumulator such as `$sum` or `$avg`.
Stages are the top-level steps in a pipeline. Each stage receives documents, changes the stream in one specific way, and passes its output to the next stage.
Course use: Exercises 07, 08, 11, 12, and Hard Mode 13.
Example pipeline syntax { $group: { _id: "$region", revenue: { $sum: "$total" } } }
Continue learning Challenge 11: Roll up regional revenue For completed orders, return revenue and order count by region, highest revenue first. Challenge 12: Compare sales channels For completed orders, calculate order count, total revenue, and average order value per channel. Sort by revenue. 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 17: Run parallel analyses For completed orders, return `byChannel` revenue summaries and the top two `byRegion` summaries in one document. Challenge 18: Map regional category leaders Using completed orders, calculate line revenue, join product categories, total revenue by region and category, then return every region-category pair ranked by revenue. 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 21: Build the commerce command report For completed orders, return one document with three arrays. `categoryPerformance` contains the top three categories with `category`, `revenue`, and `units`. `segmentPerformance` contains every customer segment with `segment`, `revenue`, `orderCount`, and `averageOrder`. `topOrder` contains the largest order with `orderId`, `region`, and `total`. Sort every report by revenue or total descending, using its name as the tie-breaker. 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 $group documentation Browse all aggregation operators