ใช้ $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
| 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 |