$group (Group Documents)
Last updated: 2026-10-09
$group (Group Documents)
$group groups documents by a specified key (_id) and applies accumulator expressions ($sum/$avg/$max...) per group. It is the most powerful pipeline stage, equivalent to SQL GROUP BY. The _id can be a field path ("$field") or compound expression defining the group key.
| Category | Core Stages |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $group: { _id: <group-key>, <field>: { <accumulator>: <expr> }, ... } }
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $group: count and total by status
db.orders.aggregate([
{ $group: { _id: "$status", count: { $sum: 1 }, total: { $sum: "$amount" } } }
])
Output:
{ "_id": "A", "count": 2, "total": 380 }
{ "_id": "B", "count": 1, "total": 130 }
📌 Notes
- _id is required; use null to group all documents
- Output fields can only be accumulators or the _id expression; recover source fields via $first/$last
- $group breaks document order; re-sort with $sort afterwards if needed
🏷️ Related Tags
💡 Related Cases
Advanced Aggregation Pipelines: Complex Expressions and Transformations
Introduction to Aggregate Pipelines: The `aggregate` Method and the Basic Stage
Hands-On: CRUD for a Blog Comment System
Change Streams: Real-Time Change Monitoring
$facet + $bucket + Text/Geospatial Search
$lookup and Associations with Multiple Sets
📚 Related Tutorials
❓ FAQ
QIs $group fully equivalent to SQL GROUP BY?
ACore-equivalent, but more flexible: _id can be any expression, and non-aggregated columns must be recovered via $first/$push rather than selected directly.
QIs _id required in $group?
AYes. _id defines the grouping key and can be a field, expression, or composite object; passing null aggregates all documents into a single group.
QIs the output field order of $group stable?
AMongoDB does not guarantee the order of $group output or the grouping sequence. Add a $sort stage afterwards to enforce ordering.