Để cập nhật nhiều tài liệu cùng lúc (multi update) một cách nguyên tử, sử dụng update() với $set và tham số multi: true (tham số thứ 4).
Tạo collection với tên trùng lặp:
> db.demo699.insertOne({Name:"Chris Brown"});
{ "acknowledged" : true, "insertedId" : ObjectId("5ea6e370551299a9f98c93a7") }
> db.demo699.insertOne({Name:"David Miller"});
{ "acknowledged" : true, "insertedId" : ObjectId("5ea6e37a551299a9f98c93a8") }
> db.demo699.insertOne({Name:"Chris Brown"});
{ "acknowledged" : true, "insertedId" : ObjectId("5ea6e381551299a9f98c93a9") }
> db.demo699.insertOne({Name:"John Doe"});
{ "acknowledged" : true, "insertedId" : ObjectId("5ea6e38a551299a9f98c93aa") }
Hiển thị tất cả:
> db.demo699.find();
Cập nhật tất cả Name="Chris Brown" thành "Adam Smith" (multi: true):
> db.demo699.update({Name:"Chris Brown"},{ $set : { Name: "Adam Smith"} }, false, true );
WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })
Kiểm tra lại (2 bản ghi Chris Brown đã thành Adam Smith):
> db.demo699.find();
Kết quả:
{ "_id" : ObjectId("5ea6e370551299a9f98c93a7"), "Name" : "Adam Smith" }
{ "_id" : ObjectId("5ea6e37a551299a9f98c93a8"), "Name" : "David Miller" }
{ "_id" : ObjectId("5ea6e381551299a9f98c93a9"), "Name" : "Adam Smith" }
{ "_id" : ObjectId("5ea6e38a551299a9f98c93aa"), "Name" : "John Doe" }