Suppose we have a MongoDB collection of products with the following structure:
[{"_id": ObjectId("61f1e6e7b6e521c6f9d6c19d"), "name": "iPhone 13",
"category": "Smartphone", "brand": "Apple", "price": 999 },
{"_id": ObjectId("61f1e6e7b6e521c6f9d6c19e"), "name": "Galaxy S21",
"category": "Smartphone", "brand": "Samsung", "price": 899 },
{ "_id": ObjectId("61f1e6e7b6e521c6f9d6c19f"), "name": "Pixel 6",
"category": "Smartphone", "brand": "Google", "price": 699 }, ....]
We want to aggregate the data to get the total count of products in each category, as well as the average price of products in each brand. We can use the following aggregation pipeline:
db.products.aggregate([
{
$facet: {
categoryCount: [
{ $stage1: { _id: "$category", count: { $stage2: 1 } } }
],
brandAveragePrice: [
{ $stage3: { _id: "$brand", averagePrice: { $stage4: "$price" } } }
]
}
}
])
Please print below the correct names of stages, instead of stage2, stage4.
Stage names in reply should be separated with a space