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

ลบและอัปเดทเอกสารที่มีอยู่ใน MongoDB ($pull)

ใช้ $pull ลบ Sub-document ออกจากอาร์เรย์และอัปเดทเอกสารพร้อมกัน

$pull ลบสมาชิกในอาร์เรย์ที่ Match เงื่อนไข และอัปเดทเอกสารใน Operation เดียว (Atomic)

ตัวอย่างข้อมูล: User Details เป็นอาร์เรย์ของ Object

> db.removeDemo.insertOne({
    "UserName": "Larry",
    "UserDetails": [ { "_id": 101, "UserEmailId": "976Larry@gmail.com" } ]
});
> db.removeDemo.insertOne({
    "UserName": "Mike",
    "UserDetails": [ { "_id": 102, "UserEmailId": "Mike121@gmail.com" } ]
});

คำสั่งลบ UserDetails ที่ _id = 102 (ของ Mike)

> db.removeDemo.update(
    { "_id": ObjectId("5cc7f9f98f9e6ff3eb0ce447") },
    { "$pull": { "UserDetails": { "_id": 102 } } }
);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

ผลลัพธ์: UserDetails ของ Mike กลายเป็น Empty Array

> db.removeDemo.find().pretty();
{ "_id" : ObjectId("5cc7f9f88f9e6ff3eb0ce446"), "UserName" : "Larry", "UserDetails" : [ { "_id" : 101, "UserEmailId" : "976Larry@gmail.com" } ] }
{ "_id" : ObjectId("5cc7f9f98f9e6ff3eb0ce447"), "UserName" : "Mike", "UserDetails" : [ ] }

รูปแบบ $pull ต่างๆ

// 1. ลบด้วยค่า Primitive
{ $pull: { tags: "old" } }

// 2. ลบด้วย Condition บน Object
{ $pull: { items: { status: "deleted" } } }

// 3. ลบหลายเงื่อนไข ($and โดยนัย)
{ $pull: { items: { status: "deleted", category: "old" } } }

// 4. ลบด้วย $in (หลายค่า)
{ $pull: { tags: { $in: ["deprecated", "legacy", "old"] } } }

ข้อสังเกต

  • $pull ลบ ทุกสมาชิก ที่ Match (ไม่ใช่แค่ตัวแรก)
  • Atomic ต่อเอกสาร - ปลอดภัยสำหรับ Concurrent Updates
  • ใช้กับอาร์เรย์ของ Object ได้โดยตรง (Match ทุกฟิลด์ที่ระบุ)