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

การอัปเดตอาร์เรย์สตริงซ้อนในอาร์เรย์ออบเจกต์ MongoDB ด้วย $pull และ Filtered Array Updates

ลบค่าเฉพาะจากอาร์เรย์ซ้อน (Nested Array) ด้วย $[]

MongoDB 3.6+ รองรับ Filtered Array Updates ผ่าน arrayFilters และตัวระบุตำแหน่ง $[] ช่วยอัปเดตอาร์เรย์ซ้อนได้อย่างแม่นยำ

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

> db.demo412.insertOne({
  "Information1": [
    { "Information2": ["John", "David"] },
    { "Information2": ["Mike"] }
  ]
});

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

> db.demo412.find();

ผลลัพธ์:

{ "_id": ObjectId("5e70f38b15dc524f70227683"), "Information1": [{ "Information2": ["John", "David"] }, { "Information2": ["Mike"] }] }

คำสั่งลบ "Mike" ออกจากทุก Information2 ในทุก Information1

> db.demo412.updateMany(
  { _id: ObjectId("5e70f38b15dc524f70227683") },
  { $pull: { 'Information1.$[].Information2': "Mike" } }
);

ผลลัพธ์: { "acknowledged": true, "matchedCount": 1, "modifiedCount": 1 }

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

> db.demo412.find();

ผลลัพธ์:

{ "_id": ObjectId("5e70f38b15dc524f70227683"), "Information1": [{ "Information2": ["John", "David"] }, { "Information2": [] }] }

คำอธิบาย

  • $[]: All positional operator - วนลูปทุกองค์ประกอบในอาร์เรย์ Information1
  • Information1.$[].Information2: เข้าถึงอาร์เรย์ Information2 ภายในทุกออบเจกต์ของ Information1
  • $pull: ลบค่า "Mike" ออกจากอาร์เรย์ Information2 ทุกตัว

รูปแบบ Filtered Array Update (เฉพาะบางออบเจกต์)

> db.demo412.updateMany(
  {},
  { $pull: { "Information1.$[elem].Information2": "Mike" } },
  { arrayFilters: [{ "elem.SomeField": "SomeValue" }] }
);

ใช้ arrayFilters กำหนดเงื่อนไขว่าจะอัปเดตออบเจกต์ไหนในอาร์เรย์นอกสุด

ตัวดำเนินการอาร์เรย์ซ้อนที่เกี่ยวข้อง

Operatorคำอธิบาย
$[]All positional - ทุกองค์ประกอบในอาร์เรย์
$[identifier]Filtered positional - เฉพาะที่ match arrayFilters
$ (positional)ออบเจกต์แรกที่ match query condition