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

CategoryGrouping & Window
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

{ $facet: { <outputField1>: [ <sub-pipeline1> ], <outputField2>: [ <sub-pipeline2> ] } }

⚙️ Parameters

sub-pipelineField 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

📚 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.
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%

🙏 帮我们做得更好

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

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