Sử dụng update() với dot notation để cập nhật trường sâu cấp 3 (Info1 → Info2 → Marks). Tạo collection:
> db.demo607.insertOne({
... id:1,
... "Info1": {
... "Name": "Chris", "Age": 21,
... "Info2": { "SubjectName": "MongoDB", "Marks": 89 }
... }
... });
{ "acknowledged" : true, "insertedId" : ObjectId("5e9742a5f57d0dc0b182d62a") }
Hiển thị dữ liệu:
> db.demo607.find();
Cập nhật Info1.Info2.Marks từ 89 → 90:
> db.demo607.update({id:1}, {$set:{"Info1.Info2.Marks":90}}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })Kết quả:
> db.demo607.find().pretty();Quy tắc dot notation:
"parent.child.grandchild"- mỗi cấp cách nhau bởi dấu chấm. MongoDB tự động tạo đường dẫn nếu chưa tồn tại (upsert behavior tùy config). Luôn dùng khi update trường lồng nhau để tránh tạo trường sai cấp độ.