สำหรับการอัพหรืออัพเดตแบบมีเงื่อนไข คุณสามารถใช้ตัวดำเนินการ $max ให้เราสร้างคอลเลกชันที่มีเอกสารก่อน
>db.conditionalUpdatesDemo.insertOne({"_id":100,"StudentFirstScore":89,"StudentSecondScore":78,"BiggestScore":89});
{ "acknowledged" : true, "insertedId" : 100 }
>db.conditionalUpdatesDemo.insertOne({"_id":101,"StudentFirstScore":305,"StudentSecondScore":560,"BiggestScore":1050});
{ "acknowledged" : true, "insertedId" : 101 }
>db.conditionalUpdatesDemo.insertOne({"_id":103,"StudentFirstScore":560,"StudentSecondScore":789,"BiggestScore":880});
{ "acknowledged" : true, "insertedId" : 103 }
Following is the query to display all documents from a collection with the help of find() method:
> db.conditionalUpdatesDemo.find().pretty(); สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้
{
"_id" : 100,
"StudentFirstScore" : 89,
"StudentSecondScore" : 78,
"BiggestScore" : 89
}
{
"_id" : 101,
"StudentFirstScore" : 305,
"StudentSecondScore" : 560,
"BiggestScore" : 1050
}
{
"_id" : 103,
"StudentFirstScore" : 560,
"StudentSecondScore" : 789,
"BiggestScore" : 880
} ต่อไปนี้เป็นข้อความค้นหาสำหรับการเพิ่มเงื่อนไขหรือการอัปเดตใน MongoDB
> db.conditionalUpdatesDemo.update( { _id: 100 }, { $max: { "BiggestScore": 150 } } );
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) ให้เราตรวจสอบช่อง “BiggestScore” ว่ามีการอัพเดทค่า 150 หรือไม่สำหรับ _id 100
> db.conditionalUpdatesDemo.find().pretty();
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้
{
"_id" : 100,
"StudentFirstScore" : 89,
"StudentSecondScore" : 78,
"BiggestScore" : 150
}
{
"_id" : 101,
"StudentFirstScore" : 305,
"StudentSecondScore" : 560,
"BiggestScore" : 1050
}
{
"_id" : 103,
"StudentFirstScore" : 560,
"StudentSecondScore" : 789,
"BiggestScore" : 880
}