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

Cập nhật tài liệu đầu tiên và thêm trường mới trong MongoDB

Khi gọi update() (hoặc updateOne()) với bộ lọc rỗng {}, MongoDB mặc định cập nhật tài liệu đầu tiên tìm thấy (theo thứ tự tự nhiên/insertion order). Kết hợp $set để thêm trường mới chỉ cho tài liệu đó.

Dữ liệu mẫu

> db.demo162.insertOne({"StudentName":"Chris"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e3684359e4f06af551997c2") }
> db.demo162.insertOne({"StudentName":"Bob"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e3684389e4f06af551997c3") }
> db.demo162.insertOne({"StudentName":"David"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e36843c9e4f06af551997c4") }

Xem dữ liệu (giả định đã có StudentAge ở tài liệu đầu)

> db.demo162.find();
{ "_id" : ObjectId("5e3684359e4f06af551997c2"), "StudentName" : "Chris", "StudentAge" : 23 }
{ "_id" : ObjectId("5e3684389e4f06af551997c3"), "StudentName" : "Bob" }
{ "_id" : ObjectId("5e36843c9e4f06af551997c4"), "StudentName" : "David" }

Cập nhật tài liệu đầu tiên: thêm StudentAge=23

> db.demo162.update({},{$set:{"StudentAge":23}},{upsert:true});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Kết quả

> db.demo162.find();
{ "_id" : ObjectId("5e3684359e4f06af551997c2"), "StudentName" : "Chris", "StudentAge" : 23 }
{ "_id" : ObjectId("5e3684389e4f06af551997c3"), "StudentName" : "Bob" }
{ "_id" : ObjectId("5e36843c9e4f06af551997c4"), "StudentName" : "David" }

Lưu ý:

  • Bộ lọc {} khớp tất cả, nhưng update() mặc định multi:false -> chỉ cập nhật 1 tài liệu đầu tiên.
  • upsert:true sẽ tạo mới nếu không có tài liệu nào khớp (điều kiện {} luôn khớp nếu collection không rỗng, nên upsert ít dùng ở đây).
  • Hiện đại: updateOne({}, {$set: {"StudentAge": 23}}).
  • Thứ tự "đầu tiên" không đảm bảo trừ khi có sort (chỉ hỗ trợ trong findOneAndUpdate).