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

  • $set creates 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 deprecated update()

Conclusion

The $set operator allows adding complex datatypes like objects and arrays to existing documents. This enables flexible schema evolution in MongoDB collections.

Updated on: 2026-03-15T03:52:51+05:30

522 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements