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 Array element in MongoDB?
To update an array element in MongoDB, you can use various operators like $set, $addToSet, or $push combined with the positional operator $ to target specific array elements.
Syntax
db.collection.update(
{"arrayField.elementField": "matchValue"},
{ $set: {"arrayField.$.newField": "newValue"} }
);
Sample Data
db.updateArrayDemo.insertOne({
"ClientDetails": [
{
"ClientName": "John",
"DeveloperDetails": []
},
{
"ClientName": "Larry",
"DeveloperDetails": []
}
]
});
{
"acknowledged": true,
"insertedId": ObjectId("5ccf465edceb9a92e6aa1960")
}
View Current Document
db.updateArrayDemo.find().pretty();
{
"_id": ObjectId("5ccf465edceb9a92e6aa1960"),
"ClientDetails": [
{
"ClientName": "John",
"DeveloperDetails": []
},
{
"ClientName": "Larry",
"DeveloperDetails": []
}
]
}
Example: Adding New Field to Array Element
Add a Technology field to Larry's client details using $addToSet ?
db.updateArrayDemo.update(
{"ClientDetails.ClientName": "Larry"},
{
$addToSet: {
"ClientDetails.$.Technology": {
"DeveloperName": "Chris",
"WorkExperience": 5
}
}
}
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Verify Update
db.updateArrayDemo.find().pretty();
{
"_id": ObjectId("5ccf465edceb9a92e6aa1960"),
"ClientDetails": [
{
"ClientName": "John",
"DeveloperDetails": []
},
{
"ClientName": "Larry",
"DeveloperDetails": [],
"Technology": [
{
"DeveloperName": "Chris",
"WorkExperience": 5
}
]
}
]
}
Key Points
-
$positional operator identifies the first matching array element -
$addToSetprevents duplicate values in arrays -
$setreplaces existing values,$pushalways adds new elements
Conclusion
Use the positional operator $ with update operators like $addToSet, $set, or $push to modify specific elements in MongoDB arrays. The $ operator targets the first array element that matches your query criteria.
Advertisements
