Để tính tổng giá trị trường Price trên tất cả tài liệu, sử dụng $group với $sum. Tạo collection:
> db.demo527.insertOne({"Price":45.5});
{ "acknowledged" : true, "insertedId" : ObjectId("5e8aff2fef4dcbee04fbbbdc") }
> db.demo527.insertOne({"Price":55.5});
{ "acknowledged" : true, "insertedId" : ObjectId("5e8aff34ef4dcbee04fbbbdd") }
> db.demo527.insertOne({"Price":100.4});
{ "acknowledged" : true, "insertedId" : ObjectId("5e8aff39ef4dcbee04fbbbde") }
> db.demo527.insertOne({"Price":200.6});
{ "acknowledged" : true, "insertedId" : ObjectId("5e8aff40ef4dcbee04fbbbdf") }
Hiển thị dữ liệu:
> db.demo527.find();
Kết quả:
Aggregation nhóm tất cả (_id: null) và tính tổng Price:
> db.demo527.aggregate([ { $group: { _id:null, totalPrice:{"$sum":"$Price"} } } ])Kết quả tổng cộng: 45.5 + 55.5 + 100.4 + 200.6 = 402:
{ "_id" : null, "totalPrice" : 402 }Giải thích:
_id: nullgom tất cả tài liệu thành 1 nhóm.$sum: "$Price"cộng dồn giá trị trường Price. Kết quả là số nguyên do MongoDB tự động chuyển đổi (402 thay vì 402.0).Mở rộng: Để giữ độ chính xác thập phân, dùng
$sum: { $toDecimal: "$Price" }(MongoDB 4.0+) hoặc lưu giá trị dạng Decimal128.