MongoDB query to insert an array element with a condition?

To insert an array element with a condition in MongoDB, use the $push operator combined with the $ positional operator to add new elements to nested arrays when specific conditions are met.

Syntax

db.collection.update(
    {"arrayField.conditionField": "value"},
    {$push: {"arrayField.$.targetArray": newElement}}
);

Sample Data

db.demo11.insertOne({
    "ListOfStudent": [
        {
            "StudentName": "Chris",
            "ListOfScore": [76, 67, 54, 89]
        }
    ]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5e0f6e34d7df943a7cec4fa1")
}

Example: Add Score with Student Name Condition

Insert a new score (98) to Chris's ListOfScore array ?

db.demo11.update(
    {"ListOfStudent.StudentName": "Chris"},
    {$push: {"ListOfStudent.$.ListOfScore": 98}}
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })

Verify Result

db.demo11.find().pretty();
{
    "_id": ObjectId("5e0f6e34d7df943a7cec4fa1"),
    "ListOfStudent": [
        {
            "StudentName": "Chris",
            "ListOfScore": [
                76,
                67,
                54,
                89,
                98
            ]
        }
    ]
}

Key Points

  • The $ positional operator identifies the first array element matching the query condition.
  • $push adds the new element to the end of the specified nested array.
  • Use dot notation to navigate through nested document structures.

Conclusion

Combine $push with the $ positional operator to conditionally insert elements into nested arrays. This approach ensures you target the correct array element based on your specified criteria.

Updated on: 2026-03-15T02:26:22+05:30

735 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements