0
0
MongoDBquery~10 mins

$facet for multiple pipelines in MongoDB - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - $facet for multiple pipelines
Input Collection
$facet Stage
Pipeline1
Results1
Combined Output Document
The $facet stage takes the input documents and runs multiple pipelines in parallel, each producing its own result array. These arrays are combined into one output document.
Execution Sample
MongoDB
db.sales.aggregate([
  {
    $facet: {
      "totalSales": [ { $group: { _id: null, total: { $sum: "$amount" } } } ],
      "countByCategory": [ { $group: { _id: "$category", count: { $sum: 1 } } } ]
    }
  }
])
This query runs two pipelines in parallel: one sums all sales amounts, the other counts sales per category.
Execution Table
StepInput DocumentsPipelineActionIntermediate ResultOutput Array
1[{amount: 10, category: 'A'}, {amount: 20, category: 'B'}, {amount: 15, category: 'A'}]totalSalesGroup all, sum amounts{_id: null, total: 45}[{_id: null, total: 45}]
2[{amount: 10, category: 'A'}, {amount: 20, category: 'B'}, {amount: 15, category: 'A'}]countByCategoryGroup by category, count[{_id: 'A', count: 2}, {_id: 'B', count: 1}][{_id: 'A', count: 2}, {_id: 'B', count: 1}]
3N/ACombineCombine pipeline outputs into one documentN/A{"totalSales": [{"_id": null, "total": 45}], "countByCategory": [{"_id": "A", "count": 2}, {"_id": "B", "count": 1}]}
💡 All pipelines processed input documents; combined output document created with results from each pipeline.
Variable Tracker
VariableStartAfter Step 1After Step 2Final
totalSales[][{_id: null, total: 45}][{_id: null, total: 45}][{_id: null, total: 45}]
countByCategory[][][{_id: 'A', count: 2}, {_id: 'B', count: 1}][{_id: 'A', count: 2}, {_id: 'B', count: 1}]
combinedOutput{}{}{}{"totalSales": [{"_id": null, "total": 45}], "countByCategory": [{"_id": "A", "count": 2}, {"_id": "B", "count": 1}]}
Key Moments - 2 Insights
Why does $facet output a single document with multiple arrays instead of multiple documents?
Because $facet runs multiple pipelines in parallel on the same input and combines their results into one document with fields named after each pipeline, as shown in execution_table row 3.
Can pipelines inside $facet affect each other’s results?
No, each pipeline runs independently on the full input documents, so their results do not affect each other, as seen in execution_table rows 1 and 2.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at Step 2, what is the intermediate result of the 'countByCategory' pipeline?
A[{_id: 'A', count: 2}, {_id: 'B', count: 1}]
B[{_id: null, total: 45}]
C[{_id: 'A', total: 25}]
D[]
💡 Hint
Check the 'Intermediate Result' column for Step 2 in the execution_table.
At which step does the combined output document get created?
AStep 1
BStep 2
CStep 3
DNo combined output is created
💡 Hint
Look for the step where 'Combine pipeline outputs into one document' is the action in execution_table.
If the input collection had no documents, what would the 'totalSales' array contain after Step 1?
A[{_id: null, total: 0}]
B[]
C[{_id: null, total: null}]
Dnull
💡 Hint
Consider how $group behaves with no input documents; check variable_tracker for 'totalSales' initial state.
Concept Snapshot
$facet stage runs multiple pipelines on the same input.
Each pipeline produces an array of results.
All arrays are combined into one output document.
Use $facet to get multiple aggregations in one query.
Each pipeline runs independently and in parallel.
Full Transcript
The $facet stage in MongoDB aggregation lets you run multiple pipelines on the same input documents at once. Each pipeline processes the documents independently and produces its own array of results. These arrays are then combined into a single output document with fields named after each pipeline. For example, one pipeline can sum all sales amounts while another counts sales by category. The execution table shows how input documents flow through each pipeline step by step, and how the final combined output document is created. Variables track the results of each pipeline separately until they are combined. Beginners often wonder why $facet outputs one document with arrays instead of multiple documents, and why pipelines do not affect each other. The key is that $facet runs pipelines in parallel and merges their results into one document. This makes $facet very useful for getting multiple summaries or analyses in a single query.