Để tính tổng (sum) trong MongoDB Aggregation Framework, bạn sử dụng toán tử $sum trong stage $group.
Ví dụ minh họa
Tạo collection và dữ liệu
> db.aggregateSumDemo.insertOne({"CustomerName":"Larry","Amount":140});
{ "acknowledged" : true, "insertedId" : ObjectId("5c8baa0680f10143d8431e18") }
> db.aggregateSumDemo.insertOne({"CustomerName":"Mike","Amount":160});
{ "acknowledged" : true, "insertedId" : ObjectId("5c8baa1380f10143d8431e19") }
> db.aggregateSumDemo.insertOne({"CustomerName":"Sam","Amount":300});
{ "acknowledged" : true, "insertedId" : ObjectId("5c8baa1c80f10143d8431e1a") }
> db.aggregateSumDemo.insertOne({"CustomerName":"David","Amount":500});
{ "acknowledged" : true, "insertedId" : ObjectId("5c8baa2580f10143d8431e1b") }
Xem tất cả documents
> db.aggregateSumDemo.find().pretty();
{
"_id" : ObjectId("5c8baa0680f10143d8431e18"),
"CustomerName" : "Larry",
"Amount" : 140
}
{
"_id" : ObjectId("5c8baa1380f10143d8431e19"),
"CustomerName" : "Mike",
"Amount" : 160
}
{
"_id" : ObjectId("5c8baa1c80f10143d8431e1a"),
"CustomerName" : "Sam",
"Amount" : 300
}
{
"_id" : ObjectId("5c8baa2580f10143d8431e1b"),
"CustomerName" : "David",
"Amount" : 500
}
Trường hợp 1: Đếm tổng số document (count)
> db.aggregateSumDemo.aggregate([
{ $group: { _id: null, "TotalCount": { $sum: 1 } } }
]);
{ "_id" : null, "TotalCount" : 4 }
$sum: 1 cộng 1 cho mỗi document → đếm tổng số document.
Trường hợp 2: Tính tổng giá trị trường Amount
> db.aggregateSumDemo.aggregate([
{ $group: { _id: null, "TotalAmount": { $sum: "$Amount" } } }
]);
{ "_id" : null, "TotalAmount" : 1100 }
$sum: "$Amount" cộng dồn giá trị trường Amount của tất cả document. 140+160+300+500 = 1100.
Nâng cao: Group theo trường + tính tổng
// Tổng Amount theo từng CustomerName
db.aggregateSumDemo.aggregate([
{ $group: { _id: "$CustomerName", total: { $sum: "$Amount" } } }
]);
{ "_id" : "Larry", "total" : 140 }
{ "_id" : "Mike", "total" : 160 }
{ "_id" : "Sam", "total" : 300 }
{ "_id" : "David", "total" : 500 }
Các accumulator khác trong $group
| Operator | Mô tả |
|---|---|
$sum | Tổng cộng |
$avg | Trung bình cộng |
$min | Giá trị nhỏ nhất |
$max | Giá trị lớn nhất |
$first | Giá trị đầu tiên (cần $sort trước) |
$last | Giá trị cuối cùng (cần $sort trước) |
$push | Gom tất cả giá trị thành mảng |
$addToSet | Gom giá trị unique thành mảng |
Pipeline hoàn chỉnh thường dùng
db.orders.aggregate([
{ $match: { status: "completed", date: { $gte: ISODate("2023-01-01") } } },
{ $group: { _id: "$customerId", totalSpent: { $sum: "$amount" }, orderCount: { $sum: 1 } } },
{ $sort: { totalSpent: -1 } },
{ $limit: 10 }
])