🍃 MongoDB Intermediate

What is the $facet stage in MongoDB aggregation?

Answer

The $facet stage allows you to create multiple independent aggregation pipelines within a single aggregation stage, processing the same input documents in different ways simultaneously. Each sub-pipeline produces its own array of result documents. Output: a single document where each field is the result array from its sub-pipeline. Example — e-commerce faceted search: db.products.aggregate([ { $match: { category: "electronics" } }, { $facet: { "priceBuckets": [ { $bucket: { groupBy: "$price", boundaries: [0,50,100,500], default: "500+" } } ], "brandCounts": [ { $group: { _id: "$brand", count: { $sum: 1 } } }, { $sort: { count: -1 } }, { $limit: 10 } ], "totalCount": [ { $count: "total" } ], "ratingDistribution": [ { $group: { _id: "$rating", count: { $sum: 1 } } } ] } } ]). All four sub-pipelines process the same electronics documents in one pass. Benefits: (1) Single database round-trip for multiple aggregations; (2) Consistent snapshot — all sub-pipelines see the same data; (3) Perfect for faceted navigation (search filters + counts). Use cases: e-commerce faceted search (price ranges, brand filter counts, rating distribution), analytics dashboards (multiple metrics in one query), reporting (multiple breakdowns of same dataset). Limitations: $facet cannot contain certain stages: $facet, $out, $indexStats, $geoNear. Memory: each sub-pipeline has its own 100MB memory limit.