0
0
MongoDBquery~3 mins

Why Array update with $[] all positional in MongoDB? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could update every item in a list with just one simple command?

The Scenario

Imagine you have a list of tasks for a project stored on paper. You want to mark all tasks as completed, but you have to cross out each one by hand, one after another.

The Problem

Doing this manually is slow and easy to miss some tasks. If the list is long, it becomes frustrating and error-prone. You might forget to update some tasks or make mistakes crossing them out.

The Solution

Using MongoDB's $[] all positional operator, you can update every item in an array at once with a single command. This saves time and ensures no item is missed.

Before vs After
Before
db.projects.updateOne({_id:1}, {$set: {'tasks.0.completed': true}})
db.projects.updateOne({_id:1}, {$set: {'tasks.1.completed': true}})
... (repeat for each task)
After
db.projects.updateOne({_id:1}, {$set: {'tasks.$[].completed': true}})
What It Enables

You can quickly and safely update all elements in an array without writing repetitive code or risking missing any item.

Real Life Example

For a shopping app, if a sale applies to all items in a user's cart, you can instantly mark every item as discounted using $[] instead of updating each product one by one.

Key Takeaways

Manual updates of array items are slow and error-prone.

$[] lets you update all array elements in one step.

This makes bulk updates simple, fast, and reliable.