เมื่อต้องการรวมค่าจากหลายเอกสารที่มีค่าซ้ำกันในฟิลด์หนึ่ง (เช่นชื่อคนเดียวกันหลายแถว) ให้ใช้ $group ร่วมกับ $sum
> db.demo512.insertOne({"Name": "Chris", "Score1": 45, "Score2": 65, "CountryName": "US"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e884d96987b6e0e9d18f588") }
> db.demo512.insertOne({"Name": "Chris", "Score1": 41, "Score2": 45, "CountryName": "US"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e884da2987b6e0e9d18f589") }
> db.demo512.insertOne({"Name": "Bob", "Score1": 75, "Score2": 55, "CountryName": "US"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e884db2987b6e0e9d18f58a") }
> db.demo512.insertOne({"Name": "Bob", "Score1": 65, "Score2": 90, "CountryName": "US"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e884dc2987b6e0e9d18f58b") }
แสดงข้อมูล:
> db.demo512.find();
{ "_id" : ObjectId("5e884d96987b6e0e9d18f588"), "Name" : "Chris", "Score1" : 45, "Score2" : 65, "CountryName" : "US" }
{ "_id" : ObjectId("5e884da2987b6e0e9d18f589"), "Name" : "Chris", "Score1" : 41, "Score2" : 45, "CountryName" : "US" }
{ "_id" : ObjectId("5e884db2987b6e0e9d18f58a"), "Name" : "Bob", "Score1" : 75, "Score2" : 55, "CountryName" : "US" }
{ "_id" : ObjectId("5e884dc2987b6e0e9d18f58b"), "Name" : "Bob", "Score1" : 65, "Score2" : 90, "CountryName" : "US" }
คิวรี Aggregation รวมคะแนนต่อคน
> db.demo512.aggregate([
... { "$group": {
... "_id": "$Name",
... "Score1": { "$sum": "$Score1" },
... "Score2": { "$sum": "$Score2" },
... "CountryName": { "$first": "$CountryName" }
... }},
... { "$project": { "_id": 0, "Name": "$_id", "Score1": 1, "Score2": 1, "CountryName": 1 }},
... { "$out": "demo513" }
... ]);
แสดงผลจากคอลเลกชันใหม่ demo513:
> db.demo513.find();
คำอธิบาย
- $group _id: "$Name": จัดกลุ่มตามชื่อ
- $sum: รวมค่า Score1 และ Score2 แยกกัน
- $first: ดึงค่า CountryName ตัวแรกในกลุ่ม (สมมติว่าเหมือนกันทั้งกลุ่ม)
- $out: บันทึกผลลัพธ์เป็นคอลเลกชันใหม่
วิธีนี้เหมาะสำหรับรายงานสรุป (reporting) เช่น ยอดขายต่อลูกค้า, คะแนนสอบรวมต่อนักเรียน