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

Cập nhật phần tử mảng khớp điều kiện với $push và positional $ trong MongoDB

Kết hợp $push với positional operator $ để thêm phần tử vào mảng con của phần tử mảng cha khớp điều kiện. Đây là pattern phổ biến cho cấu trúc dữ liệu phân cấp.

Dữ liệu mẫu

> db.demo9.insertOne({"StudentDetails":[{"StudentName":"Chris","ListOfSubject":["MySQL","Java"]}]});
{ "acknowledged" : true, "insertedId" : ObjectId("5e0f6438d7df943a7cec4f94") }

Xem dữ liệu

> db.demo9.find().pretty();
{ "_id" : ObjectId("5e0f6438d7df943a7cec4f94"), "StudentDetails" : [ { "StudentName" : "Chris", "ListOfSubject" : [ "MySQL", "Java" ] } ] }

Thêm "MongoDB" vào ListOfSubject của StudentName="Chris"

> db.demo9.update( { "StudentDetails.StudentName":"Chris"}, {$push:{"StudentDetails.$.ListOfSubject":"MongoDB"}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Kết quả

> db.demo9.find().pretty();
{ "_id" : ObjectId("5e0f6438d7df943a7cec4f94"), "StudentDetails" : [ { "StudentName" : "Chris", "ListOfSubject" : [ "MySQL", "Java", "MongoDB" ] } ] }

Lưu ý: Positional $ chỉ hoạt động khi query khớp chính xác một phần tử mảng (hoặc lấy phần tử đầu tiên khớp). Từ MongoDB 3.6+, dùng arrayFilters với $[identifier] để cập nhật nhiều phần tử hoặc điều kiện phức tạp hơn: update({...}, {$push: {"StudentDetails.$[elem].ListOfSubject": "MongoDB"}}, {arrayFilters: [{"elem.StudentName": "Chris"}]}).