Để cập nhật một phần tử cụ thể trong mảng và tăng giá trị trường của nó, sử dụng positional operator $ kết hợp $inc.
Tạo collection:
> db.demo39.insertOne({"ProductDetails":[{"ProductName":"Product-1","ProductPrice":349}]});
{ "acknowledged" : true, "insertedId" : ObjectId("5e176d54cfb11e5c34d898df") }
> db.demo39.insertOne({"ProductDetails":[{"ProductName":"Product-2","ProductPrice":998}]});
{ "acknowledged" : true, "insertedId" : ObjectId("5e176d61cfb11e5c34d898e0") }
> db.demo39.insertOne({"ProductDetails":[{"ProductName":"Product-3","ProductPrice":145}]});
{ "acknowledged" : true, "insertedId" : ObjectId("5e176d6acfb11e5c34d898e1") }
Xem dữ liệu:
> db.demo39.find();
{ "_id" : ObjectId("5e176d54cfb11e5c34d898df"), "ProductDetails" : [ { "ProductName" : "Product-1", "ProductPrice" : 349 } ] }
{ "_id" : ObjectId("5e176d61cfb11e5c34d898e0"), "ProductDetails" : [ { "ProductName" : "Product-2", "ProductPrice" : 998 } ] }
{ "_id" : ObjectId("5e176d6acfb11e5c34d898e1"), "ProductDetails" : [ { "ProductName" : "Product-3", "ProductPrice" : 145 } ] }
Tăng ProductPrice của "Product-2" lên 1 đơn vị:
> db.demo39.update({"_id" : ObjectId("5e176d61cfb11e5c34d898e0"),'ProductDetails.ProductName':"Product-2"},{$inc: {'ProductDetails.$.ProductPrice': 1}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Kết quả (Product-2 giá 999):
> db.demo39.find();
{ "_id" : ObjectId("5e176d54cfb11e5c34d898df"), "ProductDetails" : [ { "ProductName" : "Product-1", "ProductPrice" : 349 } ] }
{ "_id" : ObjectId("5e176d61cfb11e5c34d898e0"), "ProductDetails" : [ { "ProductName" : "Product-2", "ProductPrice" : 999 } ] }
{ "_id" : ObjectId("5e176d6acfb11e5c34d898e1"), "ProductDetails" : [ { "ProductName" : "Product-3", "ProductPrice" : 145 } ] }
Giải thích:
ProductDetails.ProductNametrong query: tìm tài liệu có phần tử mảng khớpProductDetails.$.ProductPricetrong update:$tham chiếu đến phần tử khớp đầu tiên$inc: tăng giá trị số
Lưu ý: Chỉ cập nhật phần tử đầu tiên khớp. Để cập nhật tất cả, dùng $[] (all positional operator, MongoDB 3.6+).