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

อัปเดตองค์ประกอบอาร์เรย์ที่ตรงเงื่อนไขด้วย $push ใน MongoDB

ใช้ $push ร่วมกับ positional operator $ เพื่อเพิ่มฟิลด์ใหม่เข้าไปในออบเจกต์ของอาร์เรย์ที่ตรงตามเงื่อนไข เริ่มต้นด้วยการสร้างคอลเลกชันตัวอย่าง:

> db.updateArrayElementDemo.insertOne(
  {
    "UserDetails": [
      { "UserName":"Chris", "UserAge":23 }
    ]
  }
);
{ "acknowledged" : true, "insertedId" : ObjectId("5ce9029378f00858fb12e90d") }

แสดงเอกสาร:

> db.updateArrayElementDemo.find().pretty();

คิวรี่เพิ่มฟิลด์ UserCountryName = "US" เข้าไปในออบเจกต์ที่ UserAge = 23:

db.updateArrayElementDemo.update(
  {"UserDetails.UserAge": 23},
  {"$push": {"UserDetails.$.UserCountryName": "US"}}
);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

ตรวจสอบเอกสารอีกครั้ง:

> db.updateArrayElementDemo.find().pretty();

คำอธิบาย:

  • {"UserDetails.UserAge": 23} - ค้นหาเอกสารที่มีอาร์เรย์ UserDetails ประกอบด้วยออบเจกต์ที่มี UserAge = 23
  • UserDetails.$.UserCountryName - ตัว $ (positional operator) อ้างถึงตำแหน่งของออบเจกต์ใน UserDetails ที่จับคู่กับเงื่อนไข
  • $push - เพิ่มค่า "US" เข้าไปในอาร์เรย์ UserCountryName (สร้างอาร์เรย์ใหม่ถ้ายังไม่มี)

หมายเหตุ: positional operator $ อัปเดตได้แค่ ออบเจกต์แรก ที่จับคู่ในอาร์เรย์