Xóa trường (field) khỏi object/document với $unset
Toán tử $unset xóa hoàn toàn một trường khỏi document. Kết hợp dot notation để xóa trường lồng sâu.
1. Dữ liệu mẫu
> db.demo467.insertOne({ _id: 101, Information: { Name: "Chris" } });
> db.demo467.insertOne({ _id: 102, Information: { Name: "David" } });
2. Xóa trường Information.Name của _id: 102
> db.demo467.update(
{ _id: 102 },
{ $unset: { "Information.Name": 1 } },
{ multi: true }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
3. Kết quả
> db.demo467.find();
{ "_id": 101, "Information": { "Name": "Chris" } }
{ "_id": 102, "Information": { } }
Lưu ý về syntax
- Giá trị
1hoặctruehoặc""đều được - chỉ cần trường tồn tại - Dùng dot notation:
"Information.Name"(trong quotes) multi: truetrongupdate()cũ =updateMany()mới
Phiên bản hiện đại (MongoDB 3.2+)
// Xóa 1 document
db.demo467.updateOne(
{ _id: 102 },
{ $unset: { "Information.Name": "" } }
);
// Xóa nhiều document
db.demo467.updateMany(
{ "Information.Name": "David" },
{ $unset: { "Information.Name": "" } }
);
Xóa cả object cha nếu rỗng (cleanup)
MongoDB không tự xóa object cha khi con rỗng. Cần làm 2 bước:
// Bước 1: Unset trường con
db.demo467.updateOne({ _id: 102 }, { $unset: { "Information.Name": "" } });
// Bước 2: Unset object cha nếu rỗng (cần aggregation hoặc check ở app)
// Hoặc dùng $set gán null rồi $unset (không khuyến khích)
So sánh $unset vs $set: null
| Hành động | $unset | $set: null |
|---|---|---|
| Trường tồn tại? | ❌ Không | ✅ Có (giá trị null) |
| { $exists: true } | false | true |
| Kích thước document | Giảm | Giữ nguyên |
Best practice: Dùng $unset khi muốn xóa hoàn toàn, $set: null khi cần giữ cấu trúc schema.