Consider a collection sales with documents like { item: 'apple', quantity: 5, price: 10 }. What will be the output of this pipeline?
[{ $match: { quantity: { $gt: 3 } } }, { $project: { item: 1, total: { $multiply: ["$quantity", "$price"] } } }][{ $match: { quantity: { $gt: 3 } } }, { $project: { item: 1, total: { $multiply: ["$quantity", "$price"] } } }]Remember that $project controls which fields appear in the output.
The $match stage filters documents where quantity > 3. The $project stage includes only item and a new field total which is quantity multiplied by price. Other fields are excluded.
In the MongoDB aggregation pipeline, which stage is used to filter documents based on a condition?
Think about which stage selects documents by condition.
The $match stage filters documents to pass only those that meet the condition to the next stage.
Which option contains a syntax error in the MongoDB aggregation pipeline stage?
{ $project: { total: { $multiply: ["$quantity", "$price"] } }Check the syntax of the $multiply operator.
The $multiply operator requires an array of expressions. Option A passes two separate arguments instead of an array.
You want to optimize a pipeline that calculates total sales and then filters for totals above 100. Which pipeline order is better?
Filtering early reduces the number of documents processed in later stages.
Option C filters documents early by quantity > 0 before calculating total and filtering by total > 100, reducing workload.
Given this pipeline:
[{ $match: { total: { $gt: 100 } } }, { $project: { total: { $multiply: ["$quantity", "$price"] } } }]Why might it return an empty result even if some documents have quantity and price values?
Think about the order stages run and when fields become available.
The pipeline has $match before $project. Stages process sequentially, so when $match executes, the 'total' field has not yet been created by the subsequent $project stage. Thus, no documents match the filter on 'total', resulting in empty output.