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
How to add an extra field in a sub document in MongoDB?
To add an extra field to a subdocument in MongoDB, use the $set operator with dot notation to target specific elements within an array. Use the array index to specify which subdocument to update.
Syntax
db.collection.update(
{ "field": "value" },
{ "$set": { "arrayField.index.newField": "newValue" } }
);
Sample Data
db.addExtraFieldDemo.insertOne({
"_id": 1,
"UserName": "Larry",
"UserOtherDetails": [
{
"UserCountryName": "US",
"UserAge": 23
},
{
"UserCountryName": "UK",
"UserAge": 24
}
]
});
{ "acknowledged": true, "insertedId": 1 }
Let us display the current document structure ?
db.addExtraFieldDemo.find().pretty();
{
"_id": 1,
"UserName": "Larry",
"UserOtherDetails": [
{
"UserCountryName": "US",
"UserAge": 23
},
{
"UserCountryName": "UK",
"UserAge": 24
}
]
}
Example: Adding Field to First Subdocument
Add an isMarried field to the first subdocument (index 0) ?
db.addExtraFieldDemo.update(
{ "_id": 1 },
{ "$set": { "UserOtherDetails.0.isMarried": true } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Verify the updated document ?
db.addExtraFieldDemo.find().pretty();
{
"_id": 1,
"UserName": "Larry",
"UserOtherDetails": [
{
"UserCountryName": "US",
"UserAge": 23,
"isMarried": true
},
{
"UserCountryName": "UK",
"UserAge": 24
}
]
}
Key Points
- Use dot notation with array index:
"arrayField.index.newField" - The
$setoperator adds new fields or updates existing ones - Array indices start from 0 (first element is index 0)
Conclusion
Use $set with dot notation and array indices to add fields to specific subdocuments. This approach allows precise targeting of array elements without affecting other subdocuments in the same array.
Advertisements
