Database
[{date:ISODate("2024-06-15T00:00:00Z"),store:"Store A",items:[{name:"item1",quantity:5,price:10.0},{name:"item2",quantity:3,price:20.0}]},{date:ISODate("2024-06-20T00:00:00Z"),store:"Store A",items:[{name:"item1",quantity:2,price:10.0},{name:"item3",quantity:4,price:15.0}]},{date:ISODate("2024-06-22T00:00:00Z"),store:"Store B",items:[{name:"item2",quantity:6,price:22.0},{name:"item3",quantity:2,price:15.0}]},{date:ISODate("2024-07-01T00:00:00Z"),store:"Store B",items:[{name:"item1",quantity:1,price:12.0},{name:"item4",quantity:5,price:8.0}]},{date:ISODate("2024-07-05T00:00:00Z"),store:"Store C",items:[{name:"item2",quantity:4,price:21.0},{name:"item3",quantity:3,price:14.0}]}]
Query
db.collection.aggregate([{"$unwind":"$items"},{"$group":{"_id":{store:"$store",month:{"$substr":["$date",0,7]}},totalRevenue:{$sum:{"$multiply":["$items.price","$items.quantity"]}},averagePrice:{"$avg":"$items.price"}}},{"$project":{_id:0,store:"$_id.store",month:"$_id.month",totalRevenue:"$totalRevenue",averagePrice:"$averagePrice"}},{$sort:{store:1,month:1}}])