0
0
MongodbHow-ToBeginner · 3 min read

How to Use $group in Aggregation in MongoDB: Syntax and Examples

In MongoDB, use the $group stage in an aggregation pipeline to group documents by a specified key and perform operations like sum, average, or count on grouped data. The $group stage requires an _id field to define the grouping key and accumulator expressions to calculate results.
📐

Syntax

The $group stage groups documents by the _id field and applies accumulator operators to compute aggregated values.

  • _id: The key to group by (can be a field or expression).
  • Accumulator fields: Use operators like $sum, $avg, $max, $min, $push, etc., to calculate values for each group.
json
{
  $group: {
    _id: <expression>,
    <field1>: { <accumulator1> : <expression1> },
    <field2>: { <accumulator2> : <expression2> },
    ...
  }
}
💻

Example

This example groups sales documents by store and calculates the total sales and the number of transactions per store.

javascript
db.sales.aggregate([
  {
    $group: {
      _id: "$store",
      totalSales: { $sum: "$amount" },
      transactionCount: { $sum: 1 }
    }
  }
])
Output
[ { "_id": "StoreA", "totalSales": 250, "transactionCount": 3 }, { "_id": "StoreB", "totalSales": 400, "transactionCount": 2 } ]
⚠️

Common Pitfalls

Common mistakes when using $group include:

  • Not specifying _id which is required to define the grouping key.
  • Using fields outside _id without an accumulator causes errors.
  • Confusing $group with $match or $sort stages.

Example of wrong usage and fix:

javascript
// Wrong: missing _id field
 db.collection.aggregate([
   { $group: { total: { $sum: "$value" } } }
 ])

// Correct: include _id to group all documents together
 db.collection.aggregate([
   { $group: { _id: null, total: { $sum: "$value" } } }
 ])
📊

Quick Reference

OperatorDescriptionExample Usage
$sumAdds values for each group{ total: { $sum: "$field" } }
$avgCalculates average value{ average: { $avg: "$field" } }
$maxFinds maximum value{ maxVal: { $max: "$field" } }
$minFinds minimum value{ minVal: { $min: "$field" } }
$pushCreates array of values{ allValues: { $push: "$field" } }
$firstGets first value in group{ firstVal: { $first: "$field" } }
$lastGets last value in group{ lastVal: { $last: "$field" } }

Key Takeaways

Always specify the _id field in $group to define how documents are grouped.
Use accumulator operators like $sum, $avg, and $push to calculate aggregated values per group.
Fields outside _id must be used with accumulators inside $group.
Grouping by null groups all documents into a single group.
Common errors come from missing _id or using fields without accumulators.