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

MongoDB เพิ่ม Element ใน Array ด้วยเงื่อนไข (Conditional $push)

การเพิ่ม Element เข้า Array ภายใน Embedded Document ที่ Match เงื่อนไข สามารถทำได้ด้วย Positional Operator $ ร่วมกับ $push เนื้อหานี้สาธิตการเพิ่มคะแนน 98 เข้า ListOfScore ของนักเรียนชื่อ "Chris"

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

> db.demo11.insertOne({
  "ListOfStudent": [{
    "StudentName": "Chris",
    "ListOfScore": [76, 67, 54, 89]
  }]
});
{ "acknowledged": true, "insertedId": ObjectId("5e0f6e34d7df943a7cec4fa1") }

แสดงข้อมูลเดิม

> db.demo11.find().pretty();
{
  "_id": ObjectId("5e0f6e34d7df943a7cec4fa1"),
  "ListOfStudent": [
    {
      "StudentName": "Chris",
      "ListOfScore": [76, 67, 54, 89]
    }
  ]
}

Query $push พร้อม Condition (Positional $)

> db.demo11.update(
  { "ListOfStudent.StudentName": "Chris" },
  { $push: { "ListOfStudent.$.ListOfScore": 98 } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })

ผลลัพธ์หลังเพิ่มคะแนน

> db.demo11.find().pretty();
{
  "_id": ObjectId("5e0f6e34d7df943a7cec4fa1"),
  "ListOfStudent": [
    {
      "StudentName": "Chris",
      "ListOfScore": [76, 67, 54, 89, 98]
    }
  ]
}

คำอธิบาย

  • Filter: {"ListOfStudent.StudentName": "Chris"} หา Doc ที่ Array ListOfStudent มี Element ที่ StudentName="Chris"
  • $push: { "ListOfStudent.$.ListOfScore": 98 }:
    • $ (Positional Operator) = Element แรกใน ListOfStudent ที่ Match Filter (คือ Chris)
    • เข้าถึง ListOfScore ภายใน Element นั้น และ Push 98 เข้าไป
  • ข้อจำกัด: $ อ้างอิงได้แค่ Element แรกที่ Match (First Match Only)
  • MongoDB 3.6+: ใช้ $[] (Filtered Positional Operator) สำหรับ Multiple Matches:
    db.demo11.update(
      { "ListOfStudent.StudentName": "Chris" },
      { $push: { "ListOfStudent.$[elem].ListOfScore": 98 } },
      { arrayFilters: [{ "elem.StudentName": "Chris" }] }
    )
  • ใช้ updateOne() / updateMany() แทน update() ใน Version ใหม่