How to add new item in nested array with MongoDB?

To add a new item to nested array elements in MongoDB, use the $set operator with dot notation to target specific fields within array objects. You can also use JavaScript-based approaches for complex updates across all array elements.

Syntax

// Method 1: Update specific array element
db.collection.updateOne(
    { query },
    { $set: { "arrayName.index.newField": "value" } }
);

// Method 2: Update all array elements using forEach
db.collection.find().forEach(function(doc) {
    // Modify document
    db.collection.replaceOne({_id: doc._id}, doc);
});

Sample Data

db.demo124.insertOne({
    "Name": "John",
    "Id": 101,
    "ProjectDetails": [
        {
            "ProjectName1": "Online Book",
            "ProjectName2": "Online Banking"
        },
        {
            "ProjectName1": "Online Library Management System",
            "ProjectName2": "School Management System"
        }
    ]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5e2f2c8b140daf4c2a3544bb")
}

Method 1: Add Field to All Array Elements

Use forEach to iterate through documents and add a new field to each array element ?

db.demo124.find().forEach(function(d) {
    for(var i = 0; i 

Method 2: Add Field to Specific Array Element

Target a specific array element by index to add a new field ?

db.demo124.updateOne(
    { "Name": "John" },
    { $set: { "ProjectDetails.0.ProjectName3": "Mobile App Development" } }
);

Verify Result

db.demo124.find().pretty();
{
    "_id": ObjectId("5e2f2c8b140daf4c2a3544bb"),
    "Name": "John",
    "Id": 101,
    "ProjectDetails": [
        {
            "ProjectName1": "Online Book",
            "ProjectName2": "Online Banking",
            "ProjectName3": "Online Snake Game"
        },
        {
            "ProjectName1": "Online Library Management System",
            "ProjectName2": "School Management System",
            "ProjectName3": "Online Snake Game"
        }
    ]
}

Key Points

  • Use forEach with replaceOne for bulk updates across all array elements
  • Use dot notation with array index for updating specific elements
  • The $set operator creates new fields if they don't exist

Conclusion

MongoDB provides multiple approaches to add items to nested arrays. Use forEach for bulk updates across all elements or $set with dot notation for precise element targeting.

Updated on: 2026-03-15T02:12:01+05:30

676 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements