ใช้ Aggregation Pipeline: $project คำนวณผลรวม (Computed Field) → $match กรองจากค่าที่คำนวณได้ เพื่อค้นหาเอกสารที่ผลรวมของ 2 ฟิลด์ตรงเงื่อนไข
สร้างคอลเลกชันและข้อมูลตัวอย่าง
> db.searchDocumentsDemo.insertOne({"Value1": 100, "Value2": 560});
{ "acknowledged": true, "insertedId": ObjectId("5cd3fe1eedc6604c74817ce9") }
> db.searchDocumentsDemo.insertOne({"Value1": 300, "Value2": 150});
{ "acknowledged": true, "insertedId": ObjectId("5cd3fe29edc6604c74817cea") }
> db.searchDocumentsDemo.insertOne({"Value1": 400, "Value2": 200});
{ "acknowledged": true, "insertedId": ObjectId("5cd3fe30edc6604c74817ceb") }
> db.searchDocumentsDemo.insertOne({"Value1": 190, "Value2": 210});
{ "acknowledged": true, "insertedId": ObjectId("5cd3fe45edc6604c74817cec") }
แสดงข้อมูลทั้งหมด
> db.searchDocumentsDemo.find().pretty();
ผลลัพธ์: 4 เอกสาร
Aggregation: คำนวณ Sum แล้ว Filter น้อยกว่า 500
> db.searchDocumentsDemo.aggregate([
{$project: {totalValue: {$add: ["$Value1", "$Value2"]}}},
{$match: {totalValue: {$lt: 500}}}
]);
ผลลัพธ์: 2 เอกสารที่ Sum < 500
{"_id": ObjectId("5cd3fe29edc6604c74817cea"), "totalValue": 450}
{"_id": ObjectId("5cd3fe45edc6604c74817cec"), "totalValue": 400}
การทำงาน
$projectสร้าง Field ใหม่totalValue= Value1 + Value2 (ใช้$add)$matchกรองเอกสารที่ totalValue < 500- เอกสารที่ 1 (100+560=660) และเอกสารที่ 3 (400+200=600) ถูกกรองออก
Operator คำนวณใน $project
| Operator | ตัวอย่าง | ผลลัพธ์ |
|---|---|---|
$add | {$add: ["$a", "$b"]} | a + b |
$subtract | {$subtract: ["$a", "$b"]} | a - b |
$multiply | {$multiply: ["$a", "$b"]} | a × b |
$divide | {$divide: ["$a", "$b"]} | a ÷ b |
$mod | {$mod: ["$a", "$b"]} | a % b |
$abs | {$abs: "$a"} | |a| |