Lỗi "multi update only works with $ operators" xảy ra khi bạn cố gắng update nhiều document (multi: true) mà không sử dụng các update operator (như $set, $inc, $push...).
Nguyên nhân
MongoDB yêu cầu mọi multi-update phải sử dụng update operators (bắt đầu bằng $). Không thể replace toàn bộ document khi multi=true.
Giải pháp: Sử dụng $set
db.yourCollectionName.update(
{ }, // query - rỗng = tất cả document
{ $set: { "fieldName": "newValue" } }, // PHẢI dùng $set
false, // upsert
true // multi = true
);
Ví dụ minh họa
Tạo collection và dữ liệu
> db.unconditionalUpdatesDemo.insertOne({"ClientName":"Larry","ClientAge":24});
{ "acknowledged" : true, "insertedId" : ObjectId("5c8eb7372f684a30fbdfd557") }
> db.unconditionalUpdatesDemo.insertOne({"ClientName":"Mike","ClientAge":26});
{ "acknowledged" : true, "insertedId" : ObjectId("5c8eb73f2f684a30fbdfd558") }
> db.unconditionalUpdatesDemo.insertOne({"ClientName":"Sam","ClientAge":27});
{ "acknowledged" : true, "insertedId" : ObjectId("5c8eb7462f684a30fbdfd559") }
> db.unconditionalUpdatesDemo.insertOne({"ClientName":"Carol","ClientAge":29});
{ "acknowledged" : true, "insertedId" : ObjectId("5c8eb7502f684a30fbdfd55a") }
Xem dữ liệu ban đầu
> db.unconditionalUpdatesDemo.find().pretty();
{
"_id" : ObjectId("5c8eb7372f684a30fbdfd557"),
"ClientName" : "Larry",
"ClientAge" : 24
}
{
"_id" : ObjectId("5c8eb73f2f684a30fbdfd558"),
"ClientName" : "Mike",
"ClientAge" : 26
}
{
"_id" : ObjectId("5c8eb7462f684a30fbdfd559"),
"ClientName" : "Sam",
"ClientAge" : 27
}
{
"_id" : ObjectId("5c8eb7502f684a30fbdfd55a"),
"ClientName" : "Carol",
"ClientAge" : 29
}
Update tất cả document: đổi ClientName thành "Robert"
> db.unconditionalUpdatesDemo.update(
{ },
{ $set: { "ClientName": "Robert" } },
false,
true
);
WriteResult({ "nMatched" : 4, "nUpserted" : 0, "nModified" : 4 })
Kiểm tra kết quả
> db.unconditionalUpdatesDemo.find().pretty();
{
"_id" : ObjectId("5c8eb7372f684a30fbdfd557"),
"ClientName" : "Robert",
"ClientAge" : 24
}
{
"_id" : ObjectId("5c8eb73f2f684a30fbdfd558"),
"ClientName" : "Robert",
"ClientAge" : 26
}
{
"_id" : ObjectId("5c8eb7462f684a30fbdfd559"),
"ClientName" : "Robert",
"ClientAge" : 27
}
{
"_id" : ObjectId("5c8eb7502f684a30fbdfd55a"),
"ClientName" : "Robert",
"ClientAge" : 29
}
Các update operator phổ biến
| Operator | Mục đích |
|---|---|
$set | Đặt giá trị trường |
$inc | Tăng/giảm giá trị số |
$push | Thêm phần tử vào mảng |
$pull | Xóa phần tử khỏi mảng |
$unset | Xóa trường |
$rename | Đổi tên trường |
Lưu ý: Từ MongoDB 3.2+, khuyến khích dùng
updateMany() thay cho update({}, ..., false, true):
db.collection.updateMany(
{ },
{ $set: { "ClientName": "Robert" } }
);