Searching for an array entry via its id in a MongoDB collection and performing update

To search for an array entry via its ID in a MongoDB collection and perform an update, use the positional $ operator along with dot notation. The $ operator identifies the matched array element, allowing you to update specific fields within that element.

Syntax

db.collection.update(
    { "arrayField._id": "targetId" },
    { $set: { "arrayField.$.fieldToUpdate": "newValue" } }
);

Create Sample Data

db.demo49.insertOne({
    "Name": "David",
    "Details": [
        {
            "_id": "D1234",
            "Subject": "MySQL"
        },
        {
            "_id": "E234",
            "Subject": "Java"
        },
        {
            "_id": "F456",
            "Subject": "Python"
        }
    ]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5e270a77cfb11e5c34d89902")
}

Display Current Documents

db.demo49.find();
{
    "_id": ObjectId("5e270a77cfb11e5c34d89902"),
    "Name": "David",
    "Details": [
        { "_id": "D1234", "Subject": "MySQL" },
        { "_id": "E234", "Subject": "Java" },
        { "_id": "F456", "Subject": "Python" }
    ]
}

Update Array Entry by ID

Update the Subject field for the array element with ID "E234" from "Java" to "MongoDB" :

db.demo49.update(
    { "Details._id": "E234" },
    { $set: { "Details.$.Subject": "MongoDB" } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })

Verify Update Result

db.demo49.find();
{
    "_id": ObjectId("5e270a77cfb11e5c34d89902"),
    "Name": "David",
    "Details": [
        { "_id": "D1234", "Subject": "MySQL" },
        { "_id": "E234", "Subject": "MongoDB" },
        { "_id": "F456", "Subject": "Python" }
    ]
}

Conclusion

Use Details._id in the query to find the specific array element, then Details.$.Subject with the positional operator to update the matched element. The $ operator automatically identifies which array element matched the query condition.

Updated on: 2026-03-15T02:49:27+05:30

154 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements