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.
Practice
$[] operator do in a MongoDB update query?Solution
Step 1: Understand the role of
The$[]$[]operator is called the all positional operator and targets all elements in an array during an update.Step 2: Compare with other array update operators
Unlike$which updates the first matched element,$[]updates every element in the array.Final Answer:
It updates every element in an array inside the matched documents. -> Option AQuick Check:
$[]updates all array elements [OK]
- Confusing $[] with $ which updates only one element
- Thinking $[] adds or removes elements
- Assuming $[] works outside arrays
scores array by 1 using $[] in MongoDB?Solution
Step 1: Identify the operator to increment array elements
The$incoperator increments numeric values. Using'scores.$[]'targets all elements in the array.Step 2: Check syntax correctness
db.collection.updateMany({}, { $inc: { 'scores.$[]': 1 } }) correctly uses$incwith$[]to increment each element by 1. Other options either use wrong operators or wrong field paths.Final Answer:
db.collection.updateMany({}, { $inc: { 'scores.$[]': 1 } }) -> Option AQuick Check:
Use $inc with 'array.$[]' to increment all elements [OK]
- Using $set instead of $inc for increment
- Trying to increment the whole array instead of elements
- Using $push which adds elements instead of updating
{ _id: 1, scores: [10, 20, 30] }, what will be the scores array after running this update?db.collection.updateOne({_id:1}, { $inc: { 'scores.$[]': 5 } })Solution
Step 1: Understand the update operation
The update uses$incwith'scores.$[]', which increments every element in thescoresarray by 5.Step 2: Calculate the new array values
Original array: [10, 20, 30]. After increment: [10+5, 20+5, 30+5] = [15, 25, 35].Final Answer:
[15, 25, 35] -> Option DQuick Check:
Increment all array elements by 5 = [15, 25, 35] [OK]
- Thinking only first element updates
- Replacing array with single value
- Not applying increment to all elements
ratings array by multiplying each by 2. Which update query will cause an error?Solution
Step 1: Analyze each update operator with $[]
$mul,$inc, and$setcan work with$[]to update array elements.$pushis for adding elements, not updating existing ones.Step 2: Identify the invalid usage
Using$pushwith$[]is invalid and causes an error because$pushexpects a field name without positional operators.Final Answer:
db.collection.updateMany({}, { $push: { 'ratings.$[]': 2 } }) -> Option CQuick Check:
$push cannot be used with $[] [OK]
- Using $push with $[] causing syntax error
- Confusing $inc and $mul usage
- Trying to multiply array directly without $[]
items as an array of objects like { _id: 1, items: [{qty: 2}, {qty: 5}] }. You want to add 3 to the qty of every item. Which update query correctly does this?Solution
Step 1: Understand the structure and goal
Each document has an arrayitemswith objects containingqty. We want to add 3 to eachqty.Step 2: Check update options
db.collection.updateMany({}, { $inc: { 'items.$[].qty': 3 } }) uses$incwithitems.$[].qty, which correctly increments theqtyfield of every object in the array. db.collection.updateMany({}, { $set: { items: { $map: { input: "$items", as: "item", in: { qty: { $add: ["$$item.qty", 3] } } } } } }) attempts to use aggregation operators like$mapin a simple update, which requires pipeline syntax (array of stages) and is invalid. db.collection.updateMany({}, { $set: { 'items.$[].qty': { $add: ['items.$[].qty', 3] } } }) is invalid syntax. db.collection.updateMany({}, { $push: { 'items.$[].qty': 3 } }) misuses$push.Final Answer:
db.collection.updateMany({}, { $inc: { 'items.$[].qty': 3 } }) -> Option BQuick Check:
Use $inc with 'array.$[].field' to update nested fields [OK]
- Using $push to update fields inside objects
- Trying to use $set with $add inside update document
- Not using $[] to target all array elements
Ready to prove it?
Pass the test and this pattern moves unknown
