Toán tử $[] (all positional operator) cập nhật **tất cả** phần tử trong mảng, khác với $ chỉ cập nhật phần tử đầu tiên khớp.
Tạo collection:
> db.demo385.insertOne({"ServerLogs": [
{"status":"InActive"},
{"status":"InActive"},
{"status":"InActive"}
]});
{ "acknowledged" : true, "insertedId" : ObjectId("5e5b6a7522064be7ab44e7f5") }
Xem dữ liệu (3 phần tử đều InActive):
> db.demo385.find().pretty();
Cập nhật **tất cả** phần tử: đổi status thành "Active":
> db.demo385.update( { "_id" : ObjectId("5e5b6a7522064be7ab44e7f5") }, { "$set": { "ServerLogs.$[].status": "Active" } } ) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })Kết quả (tất cả thành Active):
> db.demo385.find().pretty();So sánh positional operators:
$: cập nhật **phần tử đầu tiên** khớp query$[]: cập nhật **tất cả** phần tử trong mảng$[(với arrayFilters): cập nhật phần tử **thỏa mãn điều kiện** lọc]
$[] có sẵn từ MongoDB 3.6. Rất hữu ích cho cập nhật hàng loạt trong mảng.