Sử dụng dot notation kết hợp positional operator $ để cập nhật trường bên trong subdocument của mảng.
Tạo collection:
> db.demo378.insertOne({
Name: 'Chris',
details:[
{id:101,Score:56},
{id:102,Score:78}
]
});
{ "acknowledged" : true, "insertedId" : ObjectId("5e5a758a2ae06a1609a00b0f") }
Xem dữ liệu:
> db.demo378.find();
{ "_id" : ObjectId("5e5a758a2ae06a1609a00b0f"), "Name" : "Chris", "details" : [ { "id" : 101, "Score" : 56 }, { "id" : 102, "Score" : 78 } ] }
Giảm Score của phần tử có id=102 đi 8 đơn vị:
> db.demo378.update({Name: "Chris", "details.id":102 }, { $inc: { "details.$.Score": -8 } });
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Kết quả (Score 102: 78 → 70):
> db.demo378.find();
Cơ chế:
- Query
{Name: "Chris", "details.id":102}: khớp tài liệu VÀ phần tử mảng details.$.Score:$tham chiếu đến phần tử mảng đầu tiên khớp điều kiện query$inc: tăng/giảm giá trị số
Lưu ý: Chỉ cập nhật phần tử đầu tiên khớp. MongoDB 3.6+ hỗ trợ arrayFilters để cập nhật nhiều phần tử hoặc điều kiện phức tạp hơn.