Để tính tổng các trường cụ thể, hãy sử dụng tổng hợp cùng với $ sum. Trước tiên, hãy để chúng tôi tạo một bộ sưu tập với các tài liệu -
> db.getSumOfFieldsDemo.insertOne({"Customer_Id":101,"Price":50,"Status":"Active"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e06cec29e4dae213890ac55")
}
> db.getSumOfFieldsDemo.insertOne({"Customer_Id":102,"Price":200,"Status":"Inactive"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e06ced19e4dae213890ac56")
}
> db.getSumOfFieldsDemo.insertOne({"Customer_Id":101,"Price":3000,"Status":"Active"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e06cedd9e4dae213890ac57")
}
> db.getSumOfFieldsDemo.insertOne({"Customer_Id":103,"Price":400,"Status":"Active"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e06cee79e4dae213890ac58")
} Sau đây là truy vấn để hiển thị tất cả các tài liệu từ một bộ sưu tập với sự trợ giúp của phương thức find () -
> db.getSumOfFieldsDemo.find().pretty();
Điều này sẽ tạo ra kết quả sau -
{
"_id" : ObjectId("5e06cec29e4dae213890ac55"),
"Customer_Id" : 101,
"Price" : 50,
"Status" : "Active"
}
{
"_id" : ObjectId("5e06ced19e4dae213890ac56"),
"Customer_Id" : 102,
"Price" : 200,
"Status" : "Inactive"
}
{
"_id" : ObjectId("5e06cedd9e4dae213890ac57"),
"Customer_Id" : 101,
"Price" : 3000,
"Status" : "Active"
}
{
"_id" : ObjectId("5e06cee79e4dae213890ac58"),
"Customer_Id" : 103,
"Price" : 400,
"Status" : "Active"
} Sau đây là truy vấn để tính tổng các trường cụ thể dựa trên trạng thái ACTIVE -
> db.getSumOfFieldsDemo.aggregate([ { $match: { Status: "Active" } }, { $group: { _id: "$Customer_Id", TotalSum: { $sum: "$Price" } } } ]); Điều này sẽ tạo ra kết quả sau -
{ "_id" : 103, "TotalSum" : 400 }
{ "_id" : 101, "TotalSum" : 3050 }