Sử dụng $push kết hợp với positional operator $ để thêm phần tử vào mảng con (nested array) của tài liệu khớp điều kiện. Toán tử $ xác định vị trí phần tử trong mảng cha khớp query.
Dữ liệu mẫu
> db.demo11.insertOne({"ListOfStudent":[{"StudentName":"Chris","ListOfScore":[76,67,54,89]}]});
{ "acknowledged" : true, "insertedId" : ObjectId("5e0f6e34d7df943a7cec4fa1") }
Xem dữ liệu
> db.demo11.find().pretty();
{ "_id" : ObjectId("5e0f6e34d7df943a7cec4fa1"), "ListOfStudent" : [ { "StudentName" : "Chris", "ListOfScore" : [ 76, 67, 54, 89 ] } ] }
Thêm điểm 98 vào ListOfScore của StudentName="Chris"
> db.demo11.update( {"ListOfStudent.StudentName":"Chris"}, {$push:{"ListOfStudent.$.ListOfScore":98}} );
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Kết quả
> db.demo11.find().pretty();
{ "_id" : ObjectId("5e0f6e34d7df943a7cec4fa1"), "ListOfStudent" : [ { "StudentName" : "Chris", "ListOfScore" : [ 76, 67, 54, 89, 98 ] } ] }
Giải thích: Query {"ListOfStudent.StudentName":"Chris"} khớp phần tử mảng ListOfStudent có StudentName="Chris". Positional $ trong ListOfStudent.$.ListOfScore tham chiếu đến chính phần tử đó, cho phép $push vào mảng con ListOfScore. Hạn chế: $ chỉ cập nhật phần tử đầu tiên khớp. Nếu cần cập nhật nhiều phần tử, dùng $[identifier] với arrayFilters (MongoDB 3.6+).