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

วิธีลบเอกสารภายใน Array ใน MongoDB ด้วย $pull Operator

ใช้ $pull ร่วมกับ update() เพื่อลบ Element (Sub-document) ออกจาก Array ตามเงื่อนไข

รูปแบบคำสั่ง

db.collection.update(
    { query },
    { $pull: { "arrayField": { "subField": "valueToMatch" } } },
    { multi: true }  // อัปเดททุกเอกสารที่ match (legacy)
);

ตัวอย่างเต็มรูปแบบ

1. สร้างข้อมูล: Array of Objects (StudentsDetails)

> db.deleteDocumentsDemo.insertOne({
    "_id": 100,
    "StudentsDetails": [
        { "StudentId": 1, "StudentName": "John" },
        { "StudentId": 2, "StudentName": "Carol" },
        { "StudentId": 3, "StudentName": "Sam" },
        { "StudentId": 4, "StudentName": "Mike" }
    ]
});

> db.deleteDocumentsDemo.insertOne({
    "_id": 200,
    "StudentsDetails": [
        { "StudentId": 5, "StudentName": "David" },
        { "StudentId": 6, "StudentName": "Ramit" },
        { "StudentId": 7, "StudentName": "Adam" },
        { "StudentId": 8, "StudentName": "Larry" }
    ]
});

2. แสดงข้อมูลก่อนลบ

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

3. ลบ StudentName = "David" จากทุกเอกสาร (multi: true)

> db.deleteDocumentsDemo.update(
    {},
    { $pull: { "StudentsDetails": { "StudentName": "David" } } },
    { multi: true }
);
WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 1 })

4. ผลลัพธ์: David ถูกลบออกจาก _id: 200

> db.deleteDocumentsDemo.find().pretty();
{ "_id" : 100, "StudentsDetails" : [ { "StudentId": 1, "StudentName": "John" }, ... ] }
{ "_id" : 200, "StudentsDetails" : [ 
    { "StudentId": 6, "StudentName": "Ramit" },
    { "StudentId": 7, "StudentName": "Adam" },
    { "StudentId": 8, "StudentName": "Larry" }
] }

$pull Patterns

วิธีสมัยใหม่ (MongoDB 3.2+)

// ลบจาก 1 เอกสาร
db.collection.updateOne(
    { _id: 100 },
    { $pull: { "StudentsDetails": { "StudentName": "David" } } }
);

// ลบจากหลายเอกสาร
db.collection.updateMany(
    {},
    { $pull: { "StudentsDetails": { "StudentName": "David" } } }
);

สรุป

  • $pull ลบ element ใน array ตามเงื่อนไข
  • รองรับ Object query (match sub-fields)
  • ใช้ updateMany() แทน multi: true ในเวอร์ชันใหม่
  • Atomic ต่อ Document
Patternตัวอย่างคำอธิบาย
Exact match{ $pull: { arr: "value" } }ลบ element ที่เท่ากับ value
Object match{ $pull: { arr: { field: "val" } } }ลบ object ที่ field=val
Condition{ $pull: { arr: { score: { $lt: 50 } } } }ลบ object ที่ score < 50