สำหรับสิ่งนี้ คุณสามารถใช้ aggregate() ใน MongoDB ให้เราสร้างคอลเลกชันที่มีเอกสาร -
> db.demo149.insertOne({"Status":40}); { "acknowledged" : true, "insertedId" : ObjectId("5e350386fdf09dd6d08539c4") } > db.demo149.insertOne({"Status":40}); { "acknowledged" : true, "insertedId" : ObjectId("5e350388fdf09dd6d08539c5") } > db.demo149.insertOne({"Status":50}); { "acknowledged" : true, "insertedId" : ObjectId("5e35038afdf09dd6d08539c6") }
แสดงเอกสารทั้งหมดจากคอลเล็กชันโดยใช้วิธี find() -
> db.demo149.find();
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
{ "_id" : ObjectId("5e350386fdf09dd6d08539c4"), "Status" : 40 } { "_id" : ObjectId("5e350388fdf09dd6d08539c5"), "Status" : 40 } { "_id" : ObjectId("5e35038afdf09dd6d08539c6"), "Status" : 50 }
นี่คือแบบสอบถามไปยังกลุ่ม MongoDB โดย −
> db.demo149.aggregate([ ... { ... "$group": { ... "_id": null, ... "done": { ... "$push": { ... "$cond": [ ... { "$eq": [ "$Status", 40 ] }, ... { "_id": "$_id", "Status": "$Status" }, ... false ... ] ... } ... }, ... "notdone": { ... "$push": { ... "$cond": [ ... { "$eq": [ "$Status", 50 ] }, ... { "_id": "$_id", "Status": "$Status" }, ... false ... ] ... } ... } ... } ... }, ... { ... "$project": { ... "_id": 0, ... "done": { ... "$setDifference": [ "$done", [false] ] ... }, ... "notdone": { ... "$setDifference": [ "$notdone", [false] ] ... } ... } ... } ... ]);
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
{ "done" : [ { "_id" : ObjectId("5e350386fdf09dd6d08539c4"), "Status" : 40 }, { "_id" : ObjectId("5e350388fdf09dd6d08539c5"), "Status" : 40 } ], "notdone" : [ { "_id" : ObjectId("5e35038afdf09dd6d08539c6"), "Status" : 50 } ] }