Sử dụng toán tử $pull để xóa phần tử khỏi mảng dựa trên điều kiện khớp. Tạo collection với cấu trúc lồng sâu:
> db.demo715.insertOne({
... _id:1,
... details: [{
... 'id': '101',
... 'Information': [
... { 'studentid': '102', "Name":"Bob" },
... { 'studentid': '103', "Name":"Chris" }
... ]
... }]
... });
{ "acknowledged" : true, "insertedId" : 1 }
Hiển thị dữ liệu ban đầu:
> db.demo715.find();
{ "_id" : 1, "details" : [ { "id" : "101", "Information" : [ { "studentid" : "102", "Name" : "Bob" }, { "studentid" : "103", "Name" : "Chris" } ] } ] }
Xóa sinh viên có studentid='102' và Name='Bob' khỏi mảng Information:
> db.demo715.update(
... {"details.id":'101'},
... { $pull: { 'details.$.Information':{studentid:'102',"Name":"Bob"} } }
... );
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Kết quả sau xóa:
> db.demo715.find();
{ "_id" : 1, "details" : [ { "id" : "101", "Information" : [ { "studentid" : "103", "Name" : "Chris" } ] } ] }
Giải thích:
details.$: Toán tử vị trí trỏ đến phần tử trong mảngdetailskhớp điều kiệnid: '101'$pull: Xóa tất cả phần tử trong mảngInformationkhớp điều kiện- Điều kiện xóa:
{studentid:'102',"Name":"Bob"}(phải khớp cả hai)