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
Update multiple elements in an array in MongoDB?
To update multiple elements in an array in MongoDB, use the $[] all positional operator. This operator modifies all elements in the specified array field that match the update criteria.
Syntax
db.collection.update(
{ "matchCondition": "value" },
{ $set: { "arrayField.$[]": "newValue" } }
);
Sample Data
Let us first create a collection with documents ?
db.demo385.insertOne({
"ServerLogs": [
{
"status": "InActive"
},
{
"status": "InActive"
},
{
"status": "InActive"
}
]
});
{
"acknowledged": true,
"insertedId": ObjectId("5e5b6a7522064be7ab44e7f5")
}
Display all documents from the collection ?
db.demo385.find().pretty();
{
"_id": ObjectId("5e5b6a7522064be7ab44e7f5"),
"ServerLogs": [
{
"status": "InActive"
},
{
"status": "InActive"
},
{
"status": "InActive"
}
]
}
Example: Update All Array Elements
Following is the query to update multiple elements in an array in MongoDB ?
db.demo385.update(
{ "_id": ObjectId("5e5b6a7522064be7ab44e7f5") },
{ "$set": { "ServerLogs.$[].status": "Active" }}
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Verify Result
Display all documents to verify the update ?
db.demo385.find().pretty();
{
"_id": ObjectId("5e5b6a7522064be7ab44e7f5"),
"ServerLogs": [
{
"status": "Active"
},
{
"status": "Active"
},
{
"status": "Active"
}
]
}
Key Points
- The
$[]operator updates all array elements regardless of their current values. - Use
$[<identifier>]witharrayFiltersfor conditional updates on specific elements. - The update affects the entire array field in the matched document.
Conclusion
The $[] all positional operator provides an efficient way to update multiple array elements simultaneously. It's ideal when you need to apply the same modification to every element in an array.
Advertisements
