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

Cập nhật tài liệu lồng nhau (nested document) trong MongoDB

Sử dụng update() với dot notation để cập nhật trường sâu trong tài liệu lồng nhau. Tạo collection:

> db.demo595.insertOne({
...   "Information": [
...     { "_id": new ObjectId(), Name:"Chris" },
...     { _id:new ObjectId(), Name:"Robert" }
...   ]
... });
{ "acknowledged" : true, "insertedId" : ObjectId("5e93369cfd2d90c177b5bce4") }

Hiển thị dữ liệu (2 subdocument trong mảng Information):

> db.demo595.find().pretty();

Cập nhật Name của subdocument có _id cụ thể thành "David Miller":

> db.demo595.update(
...   {"Information._id":ObjectId("5e93369cfd2d90c177b5bce2")},
...   {$set:{"Information.$.Name":"David Miller"}}
... );
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Kết quả (Chris → David Miller):

> db.demo595.find().pretty();

Cơ chế:

  • Truy vấn: {"Information._id": ObjectId(...)} - tìm tài liệu cha chứa subdocument có _id này
  • Cập nhật: {$set:{"Information.$.Name":...}} - $ trỏ đến phần tử trong mảng Information khớp điều kiện truy vấn
  • Chỉ subdocument khớp _id được cập nhật