$facet (Multi-faceted Aggregation)
Last updated: 2026-10-09
$facet (Multi-faceted Aggregation)
$facet runs multiple sub-pipelines in parallel within one stage, each processing the same input documents, merging results as fields: { name: [ results ] }. Get summary stats, detail lists, and top-N in a single request instead of multiple round trips. Sub-pipelines are independent.
| Category | Grouping & Window |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $facet: { <outputField1>: [ <sub-pipeline1> ], <outputField2>: [ <sub-pipeline2> ] } }
⚙️ Parameters
| sub-pipeline | Field names mapped to sub-pipeline arrays, each processing the input independently. |
|---|
Returns:A single document whose fields hold each sub-pipeline's result array
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $facet: status breakdown plus top 5 by amount
db.orders.aggregate([
{ $facet: {
byStatus: [{ $group: { _id: '$status', n: { $sum: 1 } } }],
top5: [{ $sort: { amount: -1 } }, { $limit: 5 }]
} }
])
Output:
{ "byStatus": [ { "_id": "A", "n": 20 } ], "top5": [ { ... } ] }
📌 Notes
- Sub-pipelines cannot contain stages like $out, $merge, or $facet
- Sub-pipelines are independent, each seeing the full input
- Output is one document with an array per sub-pipeline name
🏷️ Related Tags
💡 Related Cases
Advanced Aggregation Pipelines: Complex Expressions and Transformations
Hands-On: CRUD for a Blog Comment System
$facet + $bucket + Text/Geospatial Search
$lookup and Associations with Multiple Sets
📚 Related Tutorials
❓ FAQ
QCan sub-pipelines sort inside $facet?
AYes, sub-pipelines may use regular stages like $sort and $limit.
QIs $facet faster than multiple aggregate calls?
AUsually yes: one pass serves many aggregations, cutting IO and round trips.
QWhat is the output shape of $facet?
AOne document; each sub-pipeline name maps to a result array.