Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MongoDB

การคำนวณผลรวมของสตริงตัวเลขใน MongoDB ด้วย $toInt และ $sum

แปลง String เป็น Int แล้ว Sum ใน MongoDB Aggregation

บทความนี้สาธิตการคำนวณผลรวมของฟิลด์ที่เก็บค่าเป็น String (เช่น "20", "50") โดยใช้ $toInt แปลงในขั้นตอน $group แล้ว $sum

ขั้นตอนที่ 1: สร้าง 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") }

ขั้นตอนที่ 2: แสดงข้อมูลทั้งหมด

> db.demo71.find();

ผลลัพธ์: Price เป็น String ทั้งหมด

ขั้นตอนที่ 3: Aggregation แปลงและ Sum

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

ผลลัพธ์ที่ได้

{ "_id": null, "TotalPrice": 100 }

สรุป: $toInt (MongoDB 4.0+) แปลง String -> Int ได้โดยตรงใน Pipeline ไม่ต้องใช้ $addFields แยก รวมกับ $sum ได้ใน Expression เดียว: {$sum: {$toInt: "$Price"}}