$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.

CategoryCore Stages
MongoDB Version1.0+
Example Languagemongosh (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

📚 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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏