1. Which aggregation stage is used to filter documents in the pipeline?
The dollar match stage filters documents in the aggregation pipeline, similar to the find query. It should be placed as early as possible in the pipeline to reduce the number of documents processed by subsequent stages. Using dollar match early improves performance because it reduces the data volume flowing through the pipeline. It accepts the same query operators as find, making it familiar and powerful for filtering documents based on conditions.
// Filter completed orders
db.orders.aggregate([
{ $match: { status: "completed" } },
{ $group: { _id: "$customerId", total: { $sum: "$amount" } } }
])
// Multiple conditions
db.orders.aggregate([
{ $match: { status: "completed", amount: { $gt: 100 } } }
])