🍃 MongoDB Intermediate

What is the $facet stage in MongoDB aggregation?

Why Interviewers Ask This

Candidates at the intermediate level are expected to not only know this concept but explain the trade-offs involved. Interviewers use this question to see if you can reason about design decisions, not just recall facts.

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.

Pro Tip

Demonstrate both theoretical understanding and practical experience. Say what it is, then give an example of how you actually used it in a MongoDB codebase.