Loại bỏ hoàn toàn object con bằng $unset
Toán tử $unset xóa trường khỏi document. Với object lồng nhau, chỉ định đường dẫn bằng dot notation.
Dữ liệu student lồng nhau
> db.demo348.insertOne({
"details": {
"studentDetails": { "StudentName": "Robert" }
}
});
> db.demo348.insertOne({
"details": {
"studentDetails": { "StudentName": "Mike" }
}
});
Xóa studentDetails khỏi tất cả document
> db.demo348.update(
{},
{ $unset: { "details.studentDetails": "" } },
{ multi: true }
);
Kết quả
{ "_id": ObjectId("..."), "details": { } }
{ "_id": ObjectId("..."), "details": { } }
Lưu ý:
multi: trueáp dụng cho tất cả document khớp (mặc định false trong update() cũ)- Dùng
updateMany()thay thế trong driver mới $unsetxóa hoàn toàn trường, khác với set null- Có thể xóa nhiều trường cùng lúc:
{ $unset: { "a": "", "b.c": "" } }