We use $[] to update all items inside an array in a document at once. It helps change many values without writing separate commands for each.
Array update with $[] all positional in MongoDB
db.collection.updateMany(
{ <filter> },
{ $set: { "arrayField.$[]": <newValue> } }
)The $[] is called the 'all positional operator'. It targets every element in the array.
You must specify the array field name before $[], like arrayField.$[].
tasks array to the string "done" for all users.db.users.updateMany(
{},
{ $set: { "tasks.$[]": "done" } }
)shipped field as true for every item in the items array, but only for orders with status "pending".db.orders.updateMany(
{ status: "pending" },
{ $set: { "items.$[].shipped": true } }
)prices array by 5 for all products.db.products.updateMany(
{},
{ $inc: { "prices.$[]": 5 } }
)This example creates a students collection with two documents. Each has a grades array. We add 5 points to every grade using $inc with the $[] operator.
db.students.insertMany([
{ _id: 1, name: "Alice", grades: [70, 80, 90] },
{ _id: 2, name: "Bob", grades: [60, 75, 85] }
])
// Show before update
print("Before update:")
db.students.find({}, { _id: 0, name: 1, grades: 1 }).forEach(doc => printjson(doc))
// Update: add 5 points to every grade for all students
// Using $inc with $[] to update all elements in grades array
db.students.updateMany(
{},
{ $inc: { "grades.$[]": 5 } }
)
// Show after update
print("After update:")
db.students.find({}, { _id: 0, name: 1, grades: 1 }).forEach(doc => printjson(doc))The $[] operator updates all elements in an array, unlike $ which updates only the first matching element.
Operators like $set and $inc are supported with $[] for arrays of primitives and subfields in objects.
Remember to test updates on a small dataset first to avoid unwanted changes.
$[] updates every element in an array inside documents.
It is useful when you want to change all items without looping manually.
For complex transformations, use aggregation pipeline with $map.