Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MongoDB

Tính tổng chuỗi số trong MongoDB aggregation

Sử dụng aggregation $toInt (hoặc $convert) chuyển string sang number rồi $sum. Tạo collection:

> 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ị - Price là string:

> db.demo71.find();

Aggregation chuyển đổi và tính tổng:

> db.demo71.aggregate([
   { $group: {
      _id: null,
      TotalPrice: { $sum: { $toInt: "$Price" } }
   }}
]);

Kết quả - tổng = 100:

Giải thích: $toInt (MongoDB 4.0+) chuyển string thành int trong pipeline. Cũ hơn dùng $convert: {input: "$Price", to: "int"}. $sum cộng dồn sau khi chuyển đổi. _id: null gom tất cả thành một nhóm.