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

วิธีอัปเดต MongoDB Object (Nested Field)

การอัปเดต field ที่อยู่ภายใน object (nested field) ใน MongoDB ใช้ update() ร่วมกับ $set และ dot notation เพื่อระบุ path ไปยัง field เป้าหมาย

สร้างคอลเลกชันและข้อมูลตัวอย่าง

> db.demo77.insertOne({"Details" : { "Score" : 78 } });
{ "acknowledged" : true, "insertedId" : ObjectId("5e2bd6f371bf0181ecc4228a") }

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

> db.demo77.find();

ผลลัพธ์:

{ "_id" : ObjectId("5e2bd6f371bf0181ecc4228a"), "Details" : { "Score" : 78 } }

Query อัปเดต Nested Field

> db.demo77.update(
... {'Details.Score':78},
... {$set:{'Details.Score':89}},
... {multi:true}
... );
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

คำอธิบายพารามิเตอร์:

  • {'Details.Score':78}: เงื่อนไขค้นหา (query filter) - ใช้ dot notation
  • {$set:{'Details.Score':89}}: การอัปเดต - ตั้งค่าใหม่ให้ field Details.Score
  • {multi:true}: อัปเดต ทุกเอกสาร ที่ตรงเงื่อนไข (default เป็น false = อัปเดตแค่ตัวแรก)

แสดงข้อมูลหลังอัปเดต

> db.demo77.find();

ผลลัพธ์:

{ "_id" : ObjectId("5e2bd6f371bf0181ecc4228a"), "Details" : { "Score" : 89 } }

วิธีใหม่ที่แนะนำ (MongoDB 3.2+)

// อัปเดตเอกสารเดียว
db.demo77.updateOne(
  {"Details.Score": 78},
  {$set: {"Details.Score": 89}}
)

// อัปเดตทุกเอกสารที่ตรงเงื่อนไข
db.demo77.updateMany(
  {"Details.Score": 78},
  {$set: {"Details.Score": 89}}
)

ข้อแตกต่าง: updateOne/updateMany ให้ผลลัพธ์ที่อ่านง่ายกว่า (matchedCount, modifiedCount) และเป็นมาตรฐานใหม่

เคล็ดลับ: ใช้ $inc แทน $set หากต้องการเพิ่ม/ลดค่าเลข (atomic operation): {$inc: {"Details.Score": 10}}