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

Cách hoạt động của phương thức Update() trong MongoDB để thiết lập giá trị cho toàn bộ trường

Phương thức update() kết hợp với toán tử $set cho phép cập nhật giá trị của một trường cho nhiều tài liệu cùng lúc. Khi sử dụng tùy chọn multi: true, thao tác sẽ áp dụng cho tất cả tài liệu khớp với điều kiện.

Tạo dữ liệu mẫu

> db.workingOfUpdateMethod.insertOne({"ClientCountryName" : "AUS"});
{ "acknowledged" : true, "insertedId" : ObjectId("5cd506fe2cba06f46efe9efa") }
> db.workingOfUpdateMethod.insertOne({"ClientCountryName" : "AUS"});
{ "acknowledged" : true, "insertedId" : ObjectId("5cd507022cba06f46efe9efb") }
> db.workingOfUpdateMethod.insertOne({"ClientCountryName" : "AUS"});
{ "acknowledged" : true, "insertedId" : ObjectId("5cd507022cba06f46efe9efc") }
> db.workingOfUpdateMethod.insertOne({"ClientCountryName" : "AUS"});
{ "acknowledged" : true, "insertedId" : ObjectId("5cd507032cba06f46efe9efd") }

Xem tất cả tài liệu

> db.workingOfUpdateMethod.find().pretty();
{ "_id" : ObjectId("5cd506fe2cba06f46efe9efa"), "ClientCountryName" : "AUS" }
{ "_id" : ObjectId("5cd507022cba06f46efe9efb"), "ClientCountryName" : "AUS" }
{ "_id" : ObjectId("5cd507022cba06f46efe9efc"), "ClientCountryName" : "AUS" }
{ "_id" : ObjectId("5cd507032cba06f46efe9efd"), "ClientCountryName" : "AUS" }

Cập nhật hàng loạt với multi: true

Thay đổi ClientCountryName từ "AUS" thành "UK" cho tất cả tài liệu khớp:

> db.workingOfUpdateMethod.update(
  {"ClientCountryName" : "AUS"}, 
  {$set: {"ClientCountryName" : "UK"}}, 
  {multi: true}
);
WriteResult({ "nMatched" : 4, "nUpserted" : 0, "nModified" : 4 })

Kết quả sau cập nhật

> db.workingOfUpdateMethod.find().pretty();
{ "_id" : ObjectId("5cd506fe2cba06f46efe9efa"), "ClientCountryName" : "UK" }
{ "_id" : ObjectId("5cd507022cba06f46efe9efb"), "ClientCountryName" : "UK" }
{ "_id" : ObjectId("5cd507022cba06f46efe9efc"), "ClientCountryName" : "UK" }
{ "_id" : ObjectId("5cd507032cba06f46efe9efd"), "ClientCountryName" : "UK" }

Giải thích các tham số

  • Điều kiện tìm kiếm: {"ClientCountryName" : "AUS"} - chọn tất cả tài liệu có trường này bằng "AUS"
  • Toán tử cập nhật: {$set: {"ClientCountryName" : "UK"}} - đặt giá trị mới
  • Tùy chọn multi: {multi: true} - cập nhật tất cả tài liệu khớp (mặc định là false, chỉ cập nhật 1 tài liệu)

Lưu ý phiên bản mới

Từ MongoDB 3.2+, nên sử dụng updateMany() thay cho update() với multi: true:

db.workingOfUpdateMethod.updateMany(
  {"ClientCountryName" : "AUS"}, 
  {$set: {"ClientCountryName" : "UK"}}
);