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

MongoDB Conditional Update อัปเดตเฉพาะเอกสารที่ Match เงื่อนไข

การ Conditional Update ใน MongoDB ทำได้โดยระบุ Filter Condition ใน update() และใช้ $set กำหนดค่าใหม่ เนื้อหานี้สาธิตการอัปเดต StudentMarks ของนักเรียนที่ StudentId = 103 ให้เป็น 97

ตัวอย่างข้อมูลทดสอบ

> db.demo150.insertOne({"StudentId":101,"StudentName":"Chris","StudentMarks":35});
{ "acknowledged" : true, "insertedId" : ObjectId("5e350dcdfdf09dd6d08539d3") }

> db.demo150.insertOne({"StudentId":102,"StudentName":"Chris","StudentMarks":55});
{ "acknowledged" : true, "insertedId" : ObjectId("5e350dcefdf09dd6d08539d4") }

> db.demo150.insertOne({"StudentId":103,"StudentName":"David","StudentMarks":34});
{ "acknowledged" : true, "insertedId" : ObjectId("5e350dcffdf09dd6d08539d5") }

> db.demo150.insertOne({"StudentId":104,"StudentName":"Chris","StudentMarks":38});
{ "acknowledged" : true, "insertedId" : ObjectId("5e350dd0fdf09dd6d08539d6") }

แสดงข้อมูลก่อนอัปเดต

> db.demo150.find();
{
  "_id" : ObjectId("5e350dcdfdf09dd6d08539d3"),
  "StudentId" : 101, "StudentName" : "Chris", "StudentMarks" : 35
}
{
  "_id" : ObjectId("5e350dcefdf09dd6d08539d4"),
  "StudentId" : 102, "StudentName" : "Chris", "StudentMarks" : 55
}
{
  "_id" : ObjectId("5e350dcffdf09dd6d08539d5"),
  "StudentId" : 103, "StudentName" : "David", "StudentMarks" : 34
}
{
  "_id" : ObjectId("5e350dd0fdf09dd6d08539d6"),
  "StudentId" : 104, "StudentName" : "Chris", "StudentMarks" : 38
}

Query Conditional Update

> db.demo150.update(
  {"StudentId":103},
  {$set:{"StudentMarks":97}}
);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

ผลลัพธ์หลังอัปเดต

> db.demo150.find();
{
  "_id" : ObjectId("5e350dcdfdf09dd6d08539d3"),
  "StudentId" : 101, "StudentName" : "Chris", "StudentMarks" : 35
}
{
  "_id" : ObjectId("5e350dcefdf09dd6d08539d4"),
  "StudentId" : 102, "StudentName" : "Chris", "StudentMarks" : 55
}
{
  "_id" : ObjectId("5e350dcffdf09dd6d08539d5"),
  "StudentId" : 103, "StudentName" : "David", "StudentMarks" : 97
}
{
  "_id" : ObjectId("5e350dd0fdf09dd6d08539d6"),
  "StudentId" : 104, "StudentName" : "Chris", "StudentMarks" : 38
}

คำอธิบายและ Best Practices

  • update() แบบ Legacy - MongoDB 3.2+ ควรใช้ updateOne() (Single Doc) หรือ updateMany() (Multiple Docs)
  • updateOne({"StudentId":103}, {$set:{"StudentMarks":97}}) - ชัดเจนกว่าและปลอดภัยกว่า
  • nMatched: จำนวน Doc ที่ Match Filter, nModified: จำนวนที่เปลี่ยนแปลงจริง
  • หาก Filter ไม่ Match ใดๆ: nMatched=0, nModified=0
  • ใช้ upsert: true หากต้องการสร้างใหม่เมื่อไม่พบ
  • Conditional Update สามารถใส่เงื่อนไขซับซ้อนใน Filter ได้ (เช่น $gt, $lt, $in, $and, $or)