Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Using positional operator with hierarchies in MongoDB?
The positional operator in MongoDB allows you to update array elements without knowing their exact index position. The $[] operator updates all array elements, while $ updates the first matching element.
Syntax
// Update all array elements
db.collection.update(
{ query },
{ $set: { "arrayField.$[]": newValue } }
);
// Update first matching element
db.collection.update(
{ "arrayField": matchValue },
{ $set: { "arrayField.$": newValue } }
);
Sample Data
db.demo324.insertOne({
"ListOfValues": [10, 20, 30]
});
{
"acknowledged": true,
"insertedId": ObjectId("5e516349f8647eb59e562073")
}
Let's display the document ?
db.demo324.find().pretty();
{
"_id": ObjectId("5e516349f8647eb59e562073"),
"ListOfValues": [
10,
20,
30
]
}
Example: Update All Array Elements
Using $[] to update all elements in the array ?
db.demo324.update(
{ "ListOfValues": [10, 20, 30] },
{ $set: { "ListOfValues.$[]": "MongoDB" } },
{ upsert: true }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Verify Result
db.demo324.find().pretty();
{
"_id": ObjectId("5e516349f8647eb59e562073"),
"ListOfValues": [
"MongoDB",
"MongoDB",
"MongoDB"
]
}
Key Points
-
$[]updates all elements in the matched array -
$updates only the first matching element - Useful for bulk updates without specifying individual indexes
Conclusion
The positional $[] operator provides an efficient way to update all elements in an array simultaneously. This is particularly useful when you need to apply the same transformation to every array element without iterating through individual positions.
Advertisements
