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).
| Category | Read |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
db.<collection>.aggregate(<pipeline>, { allowDiskUse: <bool> })
⚙️ Parameters
| pipeline | Array of pipeline stages, e.g. [{$match: {...}}, {$group: {...}}]. |
|---|---|
| allowDiskUse | Optional. 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
- Stage order matters — put $match early to filter as soon as possible
- Stages default to a 100MB memory cap; exceed it with allowDiskUse: true
- Reference original fields inside $group _id with a $ prefix, e.g. '$age'
🏷️ Related Tags
💡 Related Cases
📚 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.