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

Cập nhật đối tượng trong mảng lồng nhau (nested array) MongoDB

Để cập nhật đối tượng trong mảng của tài liệu, dùng update(). Tạo collection với mảng lồng nhau:

> db.updateObjects.insertOne({"CustomerId":1,"CustomerName":"Larry","TotalItems":100, "ItemDetails":[ {"NameOfItem":"Item_1","Amount":450}, {"NameOfItem":"Item_2","Amount":500}, {"NameOfItem":"Item_3","Amount":200} ] });
{ "acknowledged" : true, "insertedId" : ObjectId("5c6d688b0c3d5054b766a769") }

Hiển thị:

> db.updateObjects.find().pretty();

Tăng Amount của Item_3 thêm 130 (từ 200 thành 330) dùng $inc và positional operator $:

> db.updateObjects.update({"CustomerId":1,"ItemDetails.NameOfItem":"Item_3"}, {$inc:{"ItemDetails.$.Amount":130}}, false, true);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Kiểm tra lại:

> db.updateObjects.find().pretty();

Kết quả: Amount của Item_3 giờ là 330.