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 a field with specific datatype (list, object) in an existing MongoDB document?
To add fields with specific datatypes like objects and arrays to existing MongoDB documents, use the $set operator with update() or updateOne() methods.
Syntax
db.collection.updateOne(
{ filter },
{ $set: {
"objectField": { key: "value" },
"arrayField": [ { item1 }, { item2 } ]
}}
);
Sample Data
db.demo732.insertMany([
{ _id: 1, Language: "English" },
{ _id: 2, Language: "Hindi" }
]);
{ "acknowledged": true, "insertedIds": { "0": 1, "1": 2 } }
db.demo732.find();
{ "_id": 1, "Language": "English" }
{ "_id": 2, "Language": "Hindi" }
Example: Adding Object and Array Fields
Add an object field details and an array field studentDetails to document with _id: 1 ?
db.demo732.updateOne(
{ _id: 1 },
{ $set: {
details: { subjectName: "MongoDB" },
studentDetails: [
{ Name: "David" },
{ CountryName: "US" }
]
}}
);
{ "acknowledged": true, "matchedCount": 1, "modifiedCount": 1 }
Verify Result
db.demo732.find();
{
"_id": 1,
"Language": "English",
"details": { "subjectName": "MongoDB" },
"studentDetails": [
{ "Name": "David" },
{ "CountryName": "US" }
]
}
{ "_id": 2, "Language": "Hindi" }
Key Points
-
$setcreates new fields if they don't exist or updates existing ones - Use curly braces
{ }for object fields - Use square brackets
[ ]for array fields -
updateOne()is preferred over deprecatedupdate()
Conclusion
The $set operator allows adding complex datatypes like objects and arrays to existing documents. This enables flexible schema evolution in MongoDB collections.
Advertisements
