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

MongoDB: คำนวณผลรวม (Sum) ด้วย Aggregate

ใช้ $sum ใน aggregation pipeline เพื่อคำนวณผลรวมของฟิลด์ตัวเลข สร้างคอลเลกชันตัวอย่าง:

> db.demo337.insertOne({"Amount":100});
{ "acknowledged" : true, "insertedId" : ObjectId("5e5231e5f8647eb59e56209b") }
> db.demo337.insertOne({"Amount":500});
{ "acknowledged" : true, "insertedId" : ObjectId("5e5231e9f8647eb59e56209c") }
> db.demo337.insertOne({"Amount":400});
{ "acknowledged" : true, "insertedId" : ObjectId("5e5231ebf8647eb59e56209d") }

แสดงข้อมูล:

> db.demo337.find();

คิวรีคำนวณผลรวม Amount:

> db.demo337.aggregate([
  { $group: { _id: null, totalAmount: { $sum: "$Amount" } } }
]);

ผลลัพธ์ (100 + 500 + 400 = 1000):

{ "_id" : null, "totalAmount" : 1000 }

รายละเอียด $sum

  • ใน $group: รวมค่าของฟิลด์ในแต่ละกลุ่ม ({$sum: "$fieldName"})
  • ใน $project/$addFields: รวมค่าในอาร์เรย์ ({$sum: "$arrayField"})
  • _id: null หมายถึงรวมทั้งคอลเลกชันเป็นกลุ่มเดียว
  • รองรับ numeric types: int, long, double, decimal
  • ค่า non-numeric จะถูกข้าม (treated as 0)

ตัวอย่างเพิ่มเติม

  • นับจำนวนเอกสาร: {$sum: 1}
  • รวมเฉพาะที่ผ่านเงื่อนไข: {$sum: { $cond: [{$gt: ["$Amount", 100]}, "$Amount", 0] }}
  • รวมใน sub-group: {_id: "$category", total: {$sum: "$Amount"}}