Để tính toán tổng của chuỗi trong MongoDB, hãy sử dụng tổng hợp (). Hãy để chúng tôi tạo một bộ sưu tập với các tài liệu -
> db.demo71.insertOne({"Price":"20"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e29af210912fae76b13d76e")
}
> db.demo71.insertOne({"Price":"50"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e29af240912fae76b13d76f")
}
> db.demo71.insertOne({"Price":"20"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e29af270912fae76b13d770")
}
> db.demo71.insertOne({"Price":"10"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e29af2d0912fae76b13d771")
} 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.demo71.find();
Điều này sẽ tạo ra kết quả sau -
{ "_id" : ObjectId("5e29af210912fae76b13d76e"), "Price" : "20" }
{ "_id" : ObjectId("5e29af240912fae76b13d76f"), "Price" : "50" }
{ "_id" : ObjectId("5e29af270912fae76b13d770"), "Price" : "20" }
{ "_id" : ObjectId("5e29af2d0912fae76b13d771"), "Price" : "10" } Sau đây là truy vấn để tính tổng của chuỗi trong MongoDB -
> db.demo71.aggregate([
... {
... $group: {
... _id: null,
... TotalPrice: {
... $sum: {
... $toInt: "$Price"
... }
... }
... }
... }
... ]); Điều này sẽ tạo ra kết quả sau -
{ "_id" : null, "TotalPrice" : 100 }