MongoDB query to add new array element in document

To add new array element in a MongoDB document, use the $ positional operator along with $set in an update operation. This allows you to add a new field to a specific element within an array.

Syntax

db.collection.update(
    {"arrayField.existingField": "matchValue"},
    {"$set": {"arrayField.$.newField": "newValue"}}
);

Sample Data

db.demo222.insertOne({
    "details": [
        {
            "StudentName": "Chris",
            "StudentMarks": 78
        },
        {
            "StudentName": "David", 
            "StudentMarks": 89
        }
    ]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5e3ee31703d395bdc213472f")
}

Display Current Data

db.demo222.find().pretty();
{
    "_id": ObjectId("5e3ee31703d395bdc213472f"),
    "details": [
        {
            "StudentName": "Chris",
            "StudentMarks": 78
        },
        {
            "StudentName": "David",
            "StudentMarks": 89
        }
    ]
}

Add New Field to Array Element

Add a SubjectName field to Chris's record ?

db.demo222.update(
    {"details.StudentName": "Chris"},
    {"$set": {"details.$.SubjectName": "MongoDB"}}
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })

Verify Result

db.demo222.find().pretty();
{
    "_id": ObjectId("5e3ee31703d395bdc213472f"),
    "details": [
        {
            "StudentName": "Chris",
            "StudentMarks": 78,
            "SubjectName": "MongoDB"
        },
        {
            "StudentName": "David",
            "StudentMarks": 89
        }
    ]
}

Key Points

  • The $ positional operator targets the first matching array element.
  • Use $set to add new fields without overwriting existing ones.
  • Only the matched array element is modified; other elements remain unchanged.

Conclusion

The $ positional operator with $set efficiently adds new fields to specific array elements based on matching conditions. This approach preserves existing data while extending document structure.

Updated on: 2026-03-15T01:59:36+05:30

539 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements