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

เพิ่มฟิลด์ใหม่ใน Embedded Document ภายใน Array ใน MongoDB

บทความนี้สาธิตวิธีเพิ่มฟิลด์ใหม่เข้าไปใน Object ที่อยู่ภายใน Array โดยใช้ update() ร่วมกับ Positional Operator $ เพื่อระบุตำแหน่ง Element ใน Array ที่ต้องการอัปเดต

สร้างข้อมูลตัวอย่าง

> db.addAFieldDemo.insertOne(
  {
    "ClientName" : "Larry",
    "ClientCountryName" : "US",
    "ClientOtherDetails" : [
      {
        "ClientProjectName" : "Online Banking System"
      }
    ]
  }
);
{ "acknowledged" : true, "insertedId" : ObjectId("5cd44bdc2cba06f46efe9ee8") }

แสดงข้อมูลก่อนเพิ่มฟิลด์

> db.addAFieldDemo.find().pretty();
{
  "_id" : ObjectId("5cd44bdc2cba06f46efe9ee8"),
  "ClientName" : "Larry",
  "ClientCountryName" : "US",
  "ClientOtherDetails" : [
    {
      "ClientProjectName" : "Online Banking System"
    }
  ]
}

เพิ่มฟิลด์ isMarried เข้าไปใน Object ที่ ClientProjectName = "Online Banking System"

> db.addAFieldDemo.update(
  { ClientOtherDetails: { $elemMatch: { "ClientProjectName" : "Online Banking System" } } },
  { $set : { 'ClientOtherDetails.$.isMarried' : true } },
  true
);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

ตรวจสอบผลลัพธ์หลังเพิ่มฟิลด์

> db.addAFieldDemo.find().pretty();
{
  "_id" : ObjectId("5cd44bdc2cba06f46efe9ee8"),
  "ClientName" : "Larry",
  "ClientCountryName" : "US",
  "ClientOtherDetails" : [
    {
      "ClientProjectName" : "Online Banking System",
      "isMarried" : true
    }
  ]
}

คำอธิบายส่วนสำคัญ

  • $elemMatch: ใช้ใน Query เพื่อ Match Element ใน Array ที่ตรงเงื่อนไข
  • Positional Operator $: อ้างอิงถึง Element แรกใน Array ที่ Match Query (ClientOtherDetails.$)
  • Parameter true (upsert): สร้าง Document ใหม่หาไม่เจอ (ในที่นี้ไม่ได้ใช้งานเพราะเจอแล้ว)

กรณี Array มีหลาย Element ต้องการอัปเดตทุกตัว

ใช้ updateMany() ร่วมกับ arrayFilters (MongoDB 3.6+):

db.collection.updateMany(
  {},
  { $set: { "ClientOtherDetails.$[elem].isMarried": true } },
  { arrayFilters: [{ "elem.ClientProjectName": "Online Banking System" }] }
);