$facet for multiple pipelines in MongoDB - Time & Space Complexity
When using $facet in MongoDB, we run several pipelines at once on the same data. Understanding how this affects time helps us know how the work grows as data grows.
We want to see how the total work changes when we add more data or more pipelines.
Analyze the time complexity of the following code snippet.
db.collection.aggregate([
{
$facet: {
pipeline1: [ { $match: { status: "A" } }, { $count: "countA" } ],
pipeline2: [ { $match: { qty: { $gt: 50 } } }, { $group: { _id: "$item", total: { $sum: "$qty" } } } ]
}
}
])
This code runs two pipelines at the same time on the same collection: one counts documents with status "A", the other groups items with quantity over 50.
Look for repeated work inside the pipelines.
- Primary operation: Each pipeline scans the documents to filter and process them.
- How many times: Each pipeline processes all documents independently, so the scanning repeats for each pipeline.
As the number of documents grows, each pipeline must check more documents.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 2 x 10 = 20 operations |
| 100 | About 2 x 100 = 200 operations |
| 1000 | About 2 x 1000 = 2000 operations |
Pattern observation: The total work grows roughly linearly with data size, multiplied by the number of pipelines.
Time Complexity: O(k x n)
This means the work grows linearly with the number of documents n and the number of pipelines k inside $facet.
[X] Wrong: "Using $facet runs all pipelines in one pass, so it only scans data once no matter how many pipelines there are."
[OK] Correct: Each pipeline inside $facet runs independently, so the data is scanned separately for each pipeline, multiplying the work.
Knowing how $facet scales helps you explain performance trade-offs clearly. It shows you understand how MongoDB processes multiple tasks at once, a useful skill in real projects.
What if we added more pipelines inside $facet? How would the time complexity change?
Practice
$facet stage do in a MongoDB aggregation pipeline?Solution
Step 1: Understand the purpose of
$facet$facetallows running multiple aggregation pipelines on the same input data simultaneously.Step 2: Identify the output structure
The output is a single document containing separate arrays for each pipeline's results.Final Answer:
Runs multiple pipelines on the same input data and returns results in one document. -> Option DQuick Check:
$facet= multiple pipelines, one output document [OK]
$facet runs many pipelines at once [OK]- Thinking
$facetfilters or sorts data - Confusing
$facetwith$lookup - Assuming it returns multiple documents instead of one
$facet in a MongoDB aggregation pipeline?Solution
Step 1: Recall
$facetsyntax$facetexpects an object where each key is a pipeline name and the value is an array of pipeline stages.Step 2: Check each option
{ $facet: { pipeline1: [ { $match: {} } ], pipeline2: [ { $group: {} } ] } } correctly uses an object with arrays of stages. Options A, C, and D misuse arrays or objects for stages.Final Answer:
{ $facet: { pipeline1: [ { $match: {} } ], pipeline2: [ { $group: {} } ] } } -> Option AQuick Check:
$facetneeds named pipelines with arrays of stages [OK]
$facet [OK]- Using arrays directly instead of named pipelines
- Putting stages as objects instead of arrays
- Missing pipeline names inside
$facet
sales with documents like { item: 'apple', price: 10, quantity: 2 }, what will be the output of this aggregation?
{ $facet: { totalSales: [ { $group: { _id: null, total: { $sum: { $multiply: ["$price", "$quantity"] } } } } ], items: [ { $group: { _id: "$item", count: { $sum: "$quantity" } } } ] } }Solution
Step 1: Calculate totalSales pipeline
Multiply price (10) by quantity (2) = 20, sum is 20, grouped with _id null.Step 2: Calculate items pipeline
Group by item 'apple', sum quantity 2, so count is 2.Final Answer:
[{ totalSales: [{ _id: null, total: 20 }], items: [{ _id: 'apple', count: 2 }] }] -> Option AQuick Check:
Each pipeline returns array with grouped results [OK]
$facet outputs arrays for each pipeline [OK]- Expecting direct values instead of arrays
- Mixing up _id values in group results
- Forgetting
$multiplyinside$sum
{ $facet: { sales: { $group: { _id: "$item", total: { $sum: "$quantity" } } } } }
What is the mistake?Solution
Step 1: Check
Each pipeline inside$facetsyntax requirements$facetmust be an array of stages, not a single object.Step 2: Identify the error in the given code
The pipeline 'sales' is given as an object with$group, missing array brackets.Final Answer:
Pipeline stages inside$facetmust be arrays, not objects. -> Option CQuick Check:
$facetpipelines = arrays of stages [OK]
$facet [OK]- Using object instead of array for pipeline stages
- Assuming
$groupis disallowed inside$facet - Thinking
$facetmust be last stage
products collection in one query. Which $facet pipeline correctly achieves this?Solution
Step 1: Understand
Each facet must be a named pipeline with an array of stages.$facetstructureStep 2: Check each option
{ $facet: { avgPrice: [ { $group: { _id: null, avg: { $avg: "$price" } } } ], uniqueItems: [ { $group: { _id: "$item" } } ] } } correctly uses two pipelines: one groups to get average price, the other groups by item to get unique items. Options B, C, and D misuse arrays or operators incorrectly.Final Answer:
{ $facet: { avgPrice: [ { $group: { _id: null, avg: { $avg: "$price" } } } ], uniqueItems: [ { $group: { _id: "$item" } } ] } } -> Option BQuick Check:
Named pipelines with arrays of stages = correct$facetusage [OK]
- Using
$facetwith arrays instead of named pipelines - Trying to use aggregation operators directly inside
$facet - Not grouping properly to get unique items
Ready to prove it?
Pass the test and this pattern moves unknown
