Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MongoDB

Cách xóa phần tử khỏi mảng trong MongoDB

Để xóa một phần tử (object) khỏi mảng trong MongoDB, bạn sử dụng toán tử $pull.

Cú pháp

db.collection.update(
    { query },           // điều kiện tìm document
    { $pull: { arrayField: { condition } } }  // điều kiện xóa phần tử trong mảng
)

Ví dụ minh họa

Tạo collection và dữ liệu

> db.removeObjectFromArrayDemo.insertOne({
    "StudentName": "John",
    "StudentAcademicProjectDetails": [
        { "StudentProjectId": 101, "StudentProjectName": "Pig Dice Game" },
        { "StudentProjectId": 110, "StudentProjectName": "Library Management System" },
        { "StudentProjectId": 120, "StudentProjectName": "Phonebook Management System" }
    ]
});
{ "acknowledged" : true, "insertedId" : ObjectId("5c8ad13d6cea1f28b7aa0817") }

Xem dữ liệu ban đầu

> db.removeObjectFromArrayDemo.find().pretty();
{
    "_id" : ObjectId("5c8ad13d6cea1f28b7aa0817"),
    "StudentName" : "John",
    "StudentAcademicProjectDetails" : [
        { "StudentProjectId" : 101, "StudentProjectName" : "Pig Dice Game" },
        { "StudentProjectId" : 110, "StudentProjectName" : "Library Management System" },
        { "StudentProjectId" : 120, "StudentProjectName" : "Phonebook Management System" }
    ]
}

Xóa phần tử có StudentProjectId = 101

> db.removeObjectFromArrayDemo.update(
    { '_id': ObjectId("5c8ad13d6cea1f28b7aa0817") },
    { $pull: { "StudentAcademicProjectDetails" : { StudentProjectId: 101 } } },
    false,  // upsert
    true    // multi
);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Kiểm tra kết quả

> db.removeObjectFromArrayDemo.find().pretty();
{
    "_id" : ObjectId("5c8ad13d6cea1f28b7aa0817"),
    "StudentName" : "John",
    "StudentAcademicProjectDetails" : [
        { "StudentProjectId" : 110, "StudentProjectName" : "Library Management System" },
        { "StudentProjectId" : 120, "StudentProjectName" : "Phonebook Management System" }
    ]
}

Phần tử có StudentProjectId: 101 đã bị xóa khỏi mảng.

Các biến thể của $pull

Mục đíchCú pháp
Xóa theo giá trị chính xác{ $pull: { tags: "mongodb" } }
Xóa theo điều kiện trong object{ $pull: { items: { status: "done" } } }
Xóa nhiều giá trị{ $pull: { tags: { $in: ["old", "deprecated"] } } }
Xóa tất cả phần tử thỏa mãn điều kiện{ $pull: { scores: { $lt: 50 } } }
Lưu ý: $pull xóa tất cả phần tử trong mảng thỏa mãn điều kiện, không chỉ phần tử đầu tiên.