Bird
Raised Fist0
MongoDBquery~20 mins

$facet for multiple pipelines in MongoDB - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Facet Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate
2:00remaining
Output of $facet with two pipelines
Given the following MongoDB aggregation pipeline using $facet, what is the output?
MongoDB
db.sales.aggregate([
  {
    $facet: {
      totalSales: [
        { $group: { _id: null, total: { $sum: "$amount" } } }
      ],
      averageSales: [
        { $group: { _id: null, avg: { $avg: "$amount" } } }
      ]
    }
  }
])
A[{ "totalSales": 500, "averageSales": 50 }]
B[{ "totalSales": [{ "_id": null, "total": 500 }], "averageSales": [{ "_id": null, "avg": 50 }] }]
C[{ "totalSales": [{ "total": 500 }], "averageSales": [{ "avg": 50 }] }]
D[{ "totalSales": [{ "_id": null, "total": 50 }], "averageSales": [{ "_id": null, "avg": 500 }] }]
Attempts:
2 left
💡 Hint
Remember that each facet pipeline returns an array of documents.
📝 Syntax
intermediate
2:00remaining
Identify the syntax error in $facet usage
Which option contains a syntax error in the use of $facet in MongoDB aggregation?
MongoDB
db.collection.aggregate([
  {
    $facet: {
      pipeline1: [ { $match: { status: "A" } } ],
      pipeline2: { $group: { _id: "$cust_id", total: { $sum: "$amount" } } }
    }
  }
])
AUsing $group inside $facet is not allowed
Bpipeline1 uses $match which is invalid inside $facet
CMissing comma between pipeline1 and pipeline2
Dpipeline2 is not an array of stages, it is a single stage object
Attempts:
2 left
💡 Hint
Each pipeline inside $facet must be an array of stages.
❓ optimization
advanced
2:00remaining
Optimizing $facet pipelines for performance
You have two pipelines inside a $facet stage: one counts documents with status 'A', the other calculates average amount for status 'B'. Which option optimizes performance best?
AUse $match for status 'A' and 'B' inside each pipeline separately
BUse $project to filter status inside each pipeline
CUse a single $match stage before $facet filtering status 'A' or 'B'
DUse $group first then $match inside each pipeline
Attempts:
2 left
💡 Hint
Filtering early reduces data processed in later stages.
🔧 Debug
advanced
2:00remaining
Why does this $facet pipeline return empty arrays?
Given this aggregation, why do both facets return empty arrays?
db.orders.aggregate([
  { $facet: {
      shipped: [ { $match: { status: "shipped" } }, { $count: "count" } ],
      pending: [ { $match: { status: "pending" } }, { $count: "count" } ]
    }
  }
])
ANo documents have status 'shipped' or 'pending' in the collection
BThe $count stage is misplaced and should be outside $facet
CThe $match stages are invalid inside $facet
DThe aggregation pipeline is missing a $group stage before $count
Attempts:
2 left
💡 Hint
Empty arrays mean no documents matched the filters.
🧠 Conceptual
expert
2:00remaining
Understanding $facet output structure
What is the structure of the output document from a MongoDB aggregation pipeline using $facet with three pipelines named 'A', 'B', and 'C'?
AA single document with keys 'A', 'B', 'C', each containing an array of documents from their respective pipelines
BAn array of documents, each containing keys 'A', 'B', 'C' with single documents inside
CMultiple documents, one per pipeline, each with a key named after the pipeline
DA flat array combining all documents from pipelines 'A', 'B', and 'C'
Attempts:
2 left
💡 Hint
Think about how $facet groups results from multiple pipelines.

Practice

(1/5)
1. What does the $facet stage do in a MongoDB aggregation pipeline?
easy
A. Sorts documents in ascending or descending order.
B. Filters documents based on a condition.
C. Joins two collections together.
D. Runs multiple pipelines on the same input data and returns results in one document.

Solution

  1. Step 1: Understand the purpose of $facet

    $facet allows running multiple aggregation pipelines on the same input data simultaneously.
  2. Step 2: Identify the output structure

    The output is a single document containing separate arrays for each pipeline's results.
  3. Final Answer:

    Runs multiple pipelines on the same input data and returns results in one document. -> Option D
  4. Quick Check:

    $facet = multiple pipelines, one output document [OK]
Hint: Remember: $facet runs many pipelines at once [OK]
Common Mistakes:
  • Thinking $facet filters or sorts data
  • Confusing $facet with $lookup
  • Assuming it returns multiple documents instead of one
2. Which of the following is the correct syntax to use $facet in a MongoDB aggregation pipeline?
easy
A. { $facet: { pipeline1: [ { $match: {} } ], pipeline2: [ { $group: {} } ] } }
B. { $facet: [ { $match: {} }, { $group: {} } ] }
C. { $facet: { $match: {}, $group: {} } }
D. { $facet: { pipeline1: { $match: {} }, pipeline2: { $group: {} } } }

Solution

  1. Step 1: Recall $facet syntax

    $facet expects an object where each key is a pipeline name and the value is an array of pipeline stages.
  2. 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.
  3. Final Answer:

    { $facet: { pipeline1: [ { $match: {} } ], pipeline2: [ { $group: {} } ] } } -> Option A
  4. Quick Check:

    $facet needs named pipelines with arrays of stages [OK]
Hint: Use named keys with arrays of stages inside $facet [OK]
Common Mistakes:
  • Using arrays directly instead of named pipelines
  • Putting stages as objects instead of arrays
  • Missing pipeline names inside $facet
3. Given the collection 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" } } } ] } }
medium
A. [{ totalSales: [{ _id: null, total: 20 }], items: [{ _id: 'apple', count: 2 }] }]
B. [{ totalSales: 20, items: [{ _id: 'apple', count: 2 }] }]
C. [{ totalSales: [{ total: 20 }], items: [{ _id: 'apple', count: 2 }] }]
D. [{ totalSales: [{ _id: null, total: 12 }], items: [{ _id: 'apple', count: 2 }] }]

Solution

  1. Step 1: Calculate totalSales pipeline

    Multiply price (10) by quantity (2) = 20, sum is 20, grouped with _id null.
  2. Step 2: Calculate items pipeline

    Group by item 'apple', sum quantity 2, so count is 2.
  3. Final Answer:

    [{ totalSales: [{ _id: null, total: 20 }], items: [{ _id: 'apple', count: 2 }] }] -> Option A
  4. Quick Check:

    Each pipeline returns array with grouped results [OK]
Hint: Remember $facet outputs arrays for each pipeline [OK]
Common Mistakes:
  • Expecting direct values instead of arrays
  • Mixing up _id values in group results
  • Forgetting $multiply inside $sum
4. You wrote this aggregation but get an error:
{ $facet: { sales: { $group: { _id: "$item", total: { $sum: "$quantity" } } } } }
What is the mistake?
medium
A. The $facet stage must be the last stage in the pipeline.
B. You cannot use $group inside $facet.
C. Pipeline stages inside $facet must be arrays, not objects.
D. The field names inside $group are incorrect.

Solution

  1. Step 1: Check $facet syntax requirements

    Each pipeline inside $facet must be an array of stages, not a single object.
  2. Step 2: Identify the error in the given code

    The pipeline 'sales' is given as an object with $group, missing array brackets.
  3. Final Answer:

    Pipeline stages inside $facet must be arrays, not objects. -> Option C
  4. Quick Check:

    $facet pipelines = arrays of stages [OK]
Hint: Always wrap pipeline stages in arrays inside $facet [OK]
Common Mistakes:
  • Using object instead of array for pipeline stages
  • Assuming $group is disallowed inside $facet
  • Thinking $facet must be last stage
5. You want to get both the average price and a list of unique items from a products collection in one query. Which $facet pipeline correctly achieves this?
hard
A. { $facet: [ { $group: { _id: null, avg: { $avg: "$price" } } }, { $group: { _id: "$item" } } ] }
B. { $facet: { avgPrice: [ { $group: { _id: null, avg: { $avg: "$price" } } } ], uniqueItems: [ { $group: { _id: "$item" } } ] } }
C. { $facet: { avgPrice: { $avg: "$price" }, uniqueItems: { $addToSet: "$item" } } }
D. { $facet: { avgPrice: [ { $avg: "$price" } ], uniqueItems: [ { $addToSet: "$item" } ] } }

Solution

  1. Step 1: Understand $facet structure

    Each facet must be a named pipeline with an array of stages.
  2. Step 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.
  3. Final Answer:

    { $facet: { avgPrice: [ { $group: { _id: null, avg: { $avg: "$price" } } } ], uniqueItems: [ { $group: { _id: "$item" } } ] } } -> Option B
  4. Quick Check:

    Named pipelines with arrays of stages = correct $facet usage [OK]
Hint: Use separate pipelines with arrays for each facet [OK]
Common Mistakes:
  • Using $facet with arrays instead of named pipelines
  • Trying to use aggregation operators directly inside $facet
  • Not grouping properly to get unique items
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard