Sử dụng aggregation framework với $group và $sum trên đường dẫn trường lồng nhau.
Tạo collection
> db.summingSubDocumentDemo.insertOne({ "_id": 101, "CustomerDetails": { "CustomerPurchase": { "CustomerPurchaseAmount": 2000 } } });
{ "acknowledged": true, "insertedId": 101 }
> db.summingSubDocumentDemo.insertOne({ "_id": 102, "CustomerDetails": { "CustomerPurchase": { "CustomerPurchaseAmount": 3000 } } });
{ "acknowledged": true, "insertedId": 102 }
> db.summingSubDocumentDemo.insertOne({ "_id": 103, "CustomerDetails": { "CustomerPurchase": { "CustomerPurchaseAmount": 5000 } } });
{ "acknowledged": true, "insertedId": 103 }
Hiển thị tất cả
> db.summingSubDocumentDemo.find().pretty();
Tổng CustomerPurchaseAmount qua các sub-document
> db.summingSubDocumentDemo.aggregate([
{ $group: { _id: "", totalAmount: { $sum: "$CustomerDetails.CustomerPurchase.CustomerPurchaseAmount" } } },
{ $project: { _id: 0, totalAmount: 1 } }
]);
Kết quả:
{ "totalAmount": 10000 }
Giải thích: $sum cộng dồn giá trị từ đường dẫn dot notation CustomerDetails.CustomerPurchase.CustomerPurchaseAmount. $project cuối cùng loại bỏ _id và chỉ giữ totalAmount.