aggregate() (Aggregation Pipeline)

Last updated: 2026-10-09

aggregate() (Aggregation Pipeline)

aggregate() runs a multi-stage pipeline that groups, computes, and reshapes documents, e.g. `db.users.aggregate([{ $group: { _id: '$city', total: { $sum: 1 } } }])`. Stages such as $match, $group, $sort, and $project transform data in sequence. Far more powerful than find(), it is the go-to for reporting and pivots. The pipeline runs server-side and returns a cursor (or inline results).

CategoryRead
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

db.<collection>.aggregate(<pipeline>, { allowDiskUse: <bool> })

⚙️ Parameters

pipelineArray of pipeline stages, e.g. [{$match: {...}}, {$group: {...}}].
allowDiskUseOptional. true allows intermediate results over 100MB to spill to disk.

Returns:Cursor over the aggregation results; empty when $out/$merge write to a collection.

▶ Example

Run the commands below in your local mongosh (requires a running mongod):

// aggregate: count users grouped by city
const result = db.users.aggregate([
  { $group: { _id: '$address.city', total: { $sum: 1 } } },
  { $sort: { total: -1 } }
])
result.toArray()

Output:

[
  { _id: 'Beijing', total: 12 },
  { _id: 'Shanghai', total: 8 }
]

📌 Notes

📚 Related Tutorials

❓ FAQ

QWhat is the difference between aggregate and find?
Afind() only queries and projects; aggregate() can group, count, sum, and join — built for reporting.
QWhat if the aggregation exceeds the memory limit?
APass {allowDiskUse: true} to spill intermediate results to disk, or optimize with an early $match.
QHow do I consume aggregation results?
AIt returns a cursor — call .toArray() or iterate; with $out the cursor comes back empty as results land in a collection.
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%

🙏 帮我们做得更好

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

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