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

Cập nhật MongoDB tránh ghi đè (overwrite) trường lồng nhau

Vấn đề: Cập nhật trường lồng nhau sai cách sẽ tạo trường mới ở cấp gốc thay vì cập nhật cấp con. Tạo collection:

> db.demo601.insertOne({ id:1, userDetails: { userName:"John", userMailId:"John@gmail.com" } });
{ "acknowledged" : true, "insertedId" : ObjectId("5e95ff5ced011c280a0905c7") }
> db.demo601.insertOne({ id:2, userDetails: { userName:"Carol", userMailId:"Carol@gmail.com" } });
{ "acknowledged" : true, "insertedId" : ObjectId("5e95ff71ed011c280a0905c8") }

Hiển thị dữ liệu:

> db.demo601.find();

Cập nhật SAI (thiếu dot notation):

> db.demo601.update({_id:ObjectId("5e95ff71ed011c280a0905c8")}, {$set:{userMailId:"Carol@yahoo.com"}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Kết quả sai (tạo trường userMailId ở cấp gốc, userDetails.userMailId không đổi):


Cập nhật ĐÚNG (dùng dot notation):

> db.demo601.update({_id:ObjectId("5e95ff71ed011c280a0905c8")}, {$set:{"userDetails.userMailId":"Carol@yahoo.com"}});

Quy tắc: Luôn dùng dot notation ("parent.child") khi cập nhật trường lồng nhau. Nếu bỏ qua, MongoDB hiểu là trường ở cấp gốc.