Challenge - 5 Problems
Facet Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate2: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" } } }
]
}
}
])Attempts:
2 left
💡 Hint
Remember that each facet pipeline returns an array of documents.
✗ Incorrect
The $facet stage runs multiple pipelines and returns an object with arrays of results for each pipeline. Each pipeline's output is an array, even if it contains a single document.
📝 Syntax
intermediate2: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" } } }
}
}
])Attempts:
2 left
💡 Hint
Each pipeline inside $facet must be an array of stages.
✗ Incorrect
In $facet, each pipeline must be an array of aggregation stages. Option D has pipeline2 as a single object, not an array, causing a syntax error.
❓ optimization
advanced2: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?
Attempts:
2 left
💡 Hint
Filtering early reduces data processed in later stages.
✗ Incorrect
Applying a $match stage before $facet filters the documents once, reducing the amount of data each pipeline processes, improving performance.
🔧 Debug
advanced2: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" } ]
}
}
])Attempts:
2 left
💡 Hint
Empty arrays mean no documents matched the filters.
✗ Incorrect
If no documents match the $match conditions inside each facet pipeline, the output arrays will be empty. This usually means the collection has no documents with those statuses.
🧠 Conceptual
expert2: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'?
Attempts:
2 left
💡 Hint
Think about how $facet groups results from multiple pipelines.
✗ Incorrect
The $facet stage outputs a single document with keys for each pipeline. Each key holds an array of documents resulting from that pipeline.