Để xóa toàn bộ phần tử trong mảng lồng nhau, dùng toán tử $set gán mảng rỗng [].
Ví dụ: Collection clearingItemsInNestedArrayDemo với mảng lồng 2 cấp:
> db.clearingItemsInNestedArrayDemo.insertOne({
"StudentName": "John",
"StudentDetails": [
{
"ProjectName": "Online Banking",
"ProjectDetails": [
{ "TechnologyUsed": "Java", "TeamSize": 5 }
]
}
]
});
Xem dữ liệu:
> db.clearingItemsInNestedArrayDemo.find().pretty();
Xóa toàn bộ mảng StudentDetails:
> db.clearingItemsInNestedArrayDemo.update(
{ "StudentName": "John" },
{ $set: { "StudentDetails": [] } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Kiểm tra lại:
> db.clearingItemsInNestedArrayDemo.find().pretty();
Kết quả:
{ "_id": ObjectId(...), "StudentName": "John", "StudentDetails": [] }
Mở rộng: Nếu chỉ muốn xóa phần tử cụ thể trong mảng lồng nhau, dùng $pull kết hợp dot notation hoặc $[ (filtered positional operator, MongoDB 3.6+).