MongoDB query to update an array element matching a condition using $push?

To update an array element matching a condition using $push in MongoDB, use the positional operator $ to identify the matched array element, then apply $push to add a new field or value to that specific element.

Syntax

db.collection.update(
    {"arrayName.field": "matchValue"},
    {"$push": {"arrayName.$.newField": "newValue"}}
);

Create Sample Data

Let us first create a collection with documents ?

db.updateArrayElementDemo.insertOne(
    {
        "UserDetails":
        [
            {
                "UserName":"Chris",
                "UserAge":23
            }
        ]
    }
);
{
    "acknowledged" : true,
    "insertedId" : ObjectId("5ce9029378f00858fb12e90d")
}

Display all documents from the collection ?

db.updateArrayElementDemo.find().pretty();
{
    "_id" : ObjectId("5ce9029378f00858fb12e90d"),
    "UserDetails" : [
        {
            "UserName" : "Chris",
            "UserAge" : 23
        }
    ]
}

Example: Update Array Element Using $push

Update the array element where UserAge is 23 and add a new field using $push ?

db.updateArrayElementDemo.update(
    {"UserDetails.UserAge": 23},
    {"$push": {"UserDetails.$.UserCountryName": "US"}}
);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Verify Result

Check the updated document ?

db.updateArrayElementDemo.find().pretty();
{
    "_id" : ObjectId("5ce9029378f00858fb12e90d"),
    "UserDetails" : [
        {
            "UserName" : "Chris",
            "UserAge" : 23,
            "UserCountryName" : [
                "US"
            ]
        }
    ]
}

Key Points

  • The $ positional operator identifies the first array element that matches the query condition.
  • $push creates a new array field and adds the specified value to it.
  • If the field already exists as an array, $push appends the new value to that array.

Conclusion

Combine the positional operator $ with $push to add new fields or values to specific array elements that match your query condition. This approach ensures precise updates to nested array structures.

Updated on: 2026-03-15T01:33:20+05:30

483 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements