$facet Multi-Faceted Aggregation & Parallel Analytics
The $facet stage executes multiple independent aggregation sub-pipelines in parallel over the same input document stream in a single database query.
Aggregation Pipeline Multi-Stage Stream Stepper
Filter completed orders, aggregate total revenue by payment method, and sort highest first.
The pipeline begins by streaming documents from the orders collection into the memory pipeline buffer.
1. Formal Definition & Architecture Intent
The $facet stage processes multiple aggregation pipelines within a single stage on the same set of input documents. Each sub-pipeline outputs its own array of results, enabling search engines and dashboards to calculate faceted navigation menus, price histograms, and top categories in one round-trip.
2. Explain Like I'm 5 (Mental Model)
Imagine handing a stack of student test papers to 3 teachers at the same time: Teacher A counts how many students passed, Teacher B finds the top 5 highest scores, and Teacher C calculates the average grade. All 3 report back together in one envelope.
3. Real-World Architecture Example
E-commerce search page displaying paginated products along with facet filters (category counts, price ranges, brand counts).
{
"_id": "p1",
"category": "Hardware",
"brand": "Apple",
"price": 1999
}$facet computes the paginated product results and category filter counts in a single query pass.
4. MQL Implementation Steps
db.products.aggregate([
{ $match: { inStock: true } },
{
$facet: {
"categorized": [
{ $group: { _id: "$category", count: { $sum: 1 } } }
],
"priceRanges": [
{ $bucket: { groupBy: "$price", boundaries: [0, 100, 500, 2000], default: "Other" } }
],
"paginatedResults": [
{ $sort: { price: -1 } },
{ $skip: 0 },
{ $limit: 10 }
]
}
}
]);5. Critical Engineering Rules
| Rule / Constraint | Underlying Reason & Impact |
|---|---|
| Output Boundary (16MB) | Because all sub-pipeline results are returned in a single document, the final combined facet document must not exceed 16MB. |
| Memory Ceiling | $facet is a blocking stage; total memory across sub-pipelines is bounded by the 100MB limit. |
6. Deep Dive: Eliminating Multiple Client Query Round-Trips
Before $facet, an e-commerce page had to issue 3 or 4 separate aggregate() queries: one for products, one for brands, one for category counts. This tripled network latency and database connection overhead. $facet passes the filtered document stream directly to internal sub-pipelines in memory with zero network overhead.
// Structure of $facet output:
// {
// "categorized": [ { "_id": "Hardware", "count": 12 } ],
// "priceRanges": [ { "_id": 100, "count": 4 } ],
// "paginatedResults": [ { "_id": "p1", "price": 1999 } ]
// }7. Architectural Trade-offs
- •Computes complex dashboards and faceted navigation in a single network round-trip
- •Operates on a pre-filtered document stream without re-reading collections
- •Provides clean structured output ready for frontend UI state consumption
- •The entire composite result must fit within the 16MB BSON document limit
- •Sub-pipelines cannot reference results from sibling facets
8. Technical Interview Questions
The primary limitation is that $facet outputs all its sub-pipeline results inside a single BSON document. Therefore, the combined output across all facets must strictly fit within MongoDB's 16MB document size limit. Additionally, $facet is a blocking stage subject to the 100MB RAM limit.
9. Staff-Level Ready Answer
"The $facet stage runs multiple aggregation sub-pipelines in parallel over the same input stream in a single query. It is the industry standard for e-commerce faceted search and analytics dashboards, though the combined output must strictly remain under the 16MB BSON document limit."
10. Quick Knowledge Check
Why is $facet commonly used in e-commerce product search pages?