Skip to content
LESSON 37 / 50Advancedaggregation

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

Interactive Engine Simulator

Aggregation Pipeline Multi-Stage Stream Stepper

Filter completed orders, aggregate total revenue by payment method, and sort highest first.

Stage 1 of 4:db.orders
Stage 0: Raw Collection Scan
// 8 initial orders in collection

The pipeline begins by streaming documents from the orders collection into the memory pipeline buffer.

Memory & Output Tuples8 Documents Emitted
1. {"_id":"o101","product":"MacBook Pro M3","total":2499,"status":"completed","payment":"wire"}
2. {"_id":"o102","product":"Mechanical Keyboard","total":180,"status":"completed","payment":"card"}
3. {"_id":"o103","product":"4K UltraWide Monitor","total":850,"status":"shipped","payment":"card"}
4. {"_id":"o104","product":"Ergonomic Desk Chair","total":650,"status":"completed","payment":"wire"}
5. {"_id":"o105","product":"Headphones","total":350,"status":"cancelled","payment":"card"}
6. {"_id":"o106","product":"Thunderbolt Dock","total":280,"status":"completed","payment":"card"}
7. {"_id":"o107","product":"Studio Microphone","total":220,"status":"completed","payment":"paypal"}
8. {"_id":"o108","product":"Drawing Tablet Pro","total":750,"status":"completed","payment":"card"}
RAM boundary: 100MB per stage (pass allowDiskUse: true for disk spilling).

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

Sample BSON Documents:
Collection: db.products
{
  "_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

Step 1: Run multi-faceted search query
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 }
      ]
    }
  }
]);
Outputs a single document containing three arrays: categorized, priceRanges, and paginatedResults.

5. Critical Engineering Rules

Rule / ConstraintUnderlying 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 } ]
// }
Production Warning: Do not use $facet if one sub-pipeline produces millions of documents.

7. Architectural Trade-offs

Advantages
  • •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
Disadvantages & Gotchas
  • •The entire composite result must fit within the 16MB BSON document limit
  • •Sub-pipelines cannot reference results from sibling facets

8. Technical Interview Questions

Q1: What is the primary architectural limitation of the $facet aggregation stage?

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?