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

Xóa trường object lồng nhau trong MongoDB với $unset

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
  • $unset xó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": "" } }