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
Add a field to an embedded document in an array in MongoDB?
To add a field to an embedded document in an array in MongoDB, use the $set operator combined with the $ positional operator and $elemMatch to target the specific array element.
Syntax
db.collection.update(
{ "arrayField": { $elemMatch: { "matchField": "value" } } },
{ $set: { "arrayField.$.newField": "newValue" } }
);
Sample Data
Let us create a collection with documents ?
db.addAFieldDemo.insertOne({
"ClientName": "Larry",
"ClientCountryName": "US",
"ClientOtherDetails": [
{
"ClientProjectName": "Online Banking System"
}
]
});
{
"acknowledged": true,
"insertedId": ObjectId("5cd44bdc2cba06f46efe9ee8")
}
Display the current document ?
db.addAFieldDemo.find().pretty();
{
"_id": ObjectId("5cd44bdc2cba06f46efe9ee8"),
"ClientName": "Larry",
"ClientCountryName": "US",
"ClientOtherDetails": [
{
"ClientProjectName": "Online Banking System"
}
]
}
Example: Add Field to Embedded Document
Add an isMarried field to the embedded document in the array ?
db.addAFieldDemo.update(
{ "ClientOtherDetails": { $elemMatch: { "ClientProjectName": "Online Banking System" } } },
{ $set: { "ClientOtherDetails.$.isMarried": true } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Verify Result
Display the updated document ?
db.addAFieldDemo.find().pretty();
{
"_id": ObjectId("5cd44bdc2cba06f46efe9ee8"),
"ClientName": "Larry",
"ClientCountryName": "US",
"ClientOtherDetails": [
{
"ClientProjectName": "Online Banking System",
"isMarried": true
}
]
}
Key Points
-
$elemMatchlocates the array element matching the specified criteria. -
$positional operator identifies the matched array element's position. -
$setadds the new field to the targeted embedded document.
Conclusion
Use $elemMatch with the $ positional operator to precisely target and add fields to specific embedded documents within arrays. This approach ensures only the matching array element is modified.
Advertisements
