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
Push new key element into subdocument of MongoDB?
To add new fields to a subdocument in MongoDB, use the $set operator with dot notation to target the specific subdocument field.
Syntax
db.collectionName.update(
{"_id": ObjectId("yourObjectId")},
{$set: {"outerField.newFieldName": "value"}}
);
Sample Data
Let us create a collection with a document containing an empty subdocument ?
db.pushNewKeyDemo.insertOne({
"UserId": 100,
"UserDetails": {}
});
{
"acknowledged": true,
"insertedId": ObjectId("5cda58f5b50a6c6dd317adbf")
}
View the current document ?
db.pushNewKeyDemo.find();
{"_id": ObjectId("5cda58f5b50a6c6dd317adbf"), "UserId": 100, "UserDetails": {}}
Example: Adding New Field to Subdocument
Add a "UserName" field to the UserDetails subdocument ?
db.pushNewKeyDemo.update(
{"_id": ObjectId("5cda58f5b50a6c6dd317adbf")},
{$set: {"UserDetails.UserName": "David Miller"}}
);
WriteResult({"nMatched": 1, "nUpserted": 0, "nModified": 1})
Verify the updated document ?
db.pushNewKeyDemo.find();
{"_id": ObjectId("5cda58f5b50a6c6dd317adbf"), "UserId": 100, "UserDetails": {"UserName": "David Miller"}}
Adding Multiple Fields
You can add multiple fields to a subdocument in a single operation ?
db.pushNewKeyDemo.update(
{"_id": ObjectId("5cda58f5b50a6c6dd317adbf")},
{$set: {
"UserDetails.Age": 30,
"UserDetails.City": "New York"
}}
);
Conclusion
Use $set with dot notation to add new fields to subdocuments. The dot notation format "parentField.newField" allows precise targeting of subdocument properties without affecting other fields.
Advertisements
