Dùng update() với positional notation. Tạo collection mảng lồng nhau:
> db.updateObjectDemo.insertOne(
{
id : 101,
"StudentDetails": [
[ {"StudentName": "John"}, {"StudentName": "Chris"} ],
[ {"StudentName": "Carol"}, {"StudentName": "David"} ]
]
}
);
{ "acknowledged" : true, "insertedId" : ObjectId("5ccdcd9b685b30d09a7111e0") }
Hiển thị document:
> db.updateObjectDemo.find().pretty();
Kết quả:
Cập nhật object tại index [1,1] (David → Mike):
> db.updateObjectDemo.update({"id":101},{$set:{"StudentDetails.1.1.StudentName":"Mike"}}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })Kiểm tra lại:
> db.updateObjectDemo.find().pretty();Kết quả (David đã thành Mike):