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

ลบ Object ออกจาก Array ใน MongoDB ด้วย $pull

ใช้ Operator $pull เพื่อลบ Element (Object) ออกจาก Array ตามเงื่อนไข

ไวยากรณ์


db.yourCollectionName.update(
    {'_id': ObjectId("...")},
    {$pull: {"yourArrayName": {"yourArrayFieldName": yourValue}}},
    false, true
);

สร้างข้อมูลตัวอย่าง


> db.removeObject.insertOne({
    "CustomerName": "Maxwell",
    "CustomerAge": 23,
    "CustomerDetails": [
        {"CustomerId": 100, "CustomerProduct": "Product-1"},
        {"CustomerId": 150, "CustomerProduct": "Product-2"},
        {"CustomerId": 200, "CustomerProduct": "Product-3"}
    ]
});
{ "acknowledged" : true, "insertedId" : ObjectId("5c6ea036a0c51185aefbd14f") }

แสดงเอกสารก่อนลบ


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

ลบ Object ที่ CustomerId = 150


> db.removeObject.update(
    {'_id': ObjectId("5c6ea036a0c51185aefbd14f")},
    {$pull: {"CustomerDetails": {"CustomerId": 150}}},
    false, true
);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

ตรวจสอบหลังลบ


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

{
    "CustomerName" : "Maxwell",
    "CustomerAge" : 23,
    "CustomerDetails" : [
        {"CustomerId" : 100, "CustomerProduct" : "Product-1"},
        {"CustomerId" : 200, "CustomerProduct" : "Product-3"}
    ]
}

Object ที่มี CustomerId: 150 ถูกลบออกจาก Array CustomerDetails แล้ว