0
0
MongoDBquery~5 mins

Array update with $[] all positional in MongoDB

Choose your learning style9 modes available
Introduction

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.

You want to increase the price of all products in a shopping cart by 10%.
You need to mark all tasks in a to-do list as completed.
You want to add a tag to every comment in a blog post.
You want to reset the status of all devices in a user's profile.
Syntax
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.$[].

Examples
This sets every element in the tasks array to the string "done" for all users.
MongoDB
db.users.updateMany(
  {},
  { $set: { "tasks.$[]": "done" } }
)
This marks the shipped field as true for every item in the items array, but only for orders with status "pending".
MongoDB
db.orders.updateMany(
  { status: "pending" },
  { $set: { "items.$[].shipped": true } }
)
This increases every number inside the prices array by 5 for all products.
MongoDB
db.products.updateMany(
  {},
  { $inc: { "prices.$[]": 5 } }
)
Sample Program

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.

MongoDB
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))
OutputSuccess
Important Notes

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.

Summary

$[] 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.