Database
db={"customer":[{"_id":1,"name":"Alice","transactions":[{_id:"tx1",date:ISODate("2024-01-01"),amount:100},{_id:"tx2",date:ISODate("2024-01-02"),amount:200},{_id:"tx3",date:ISODate("2024-02-01"),amount:300},{_id:"tx4",date:ISODate("2024-03-01"),amount:400}]},{"_id":2,"name":"Bob","transactions":[{_id:"tx5",date:ISODate("2024-02-02"),amount:1000},{_id:"tx6",date:ISODate("2024-03-03"),amount:1000}]}]}
Query
db.customer.aggregate([{"$unwind":"$transactions"},{"$group":{"_id":{$dateTrunc:{date:"$transactions.date",unit:"month"}},"totalAmount":{"$sum":"$transactions.amount"}}}])