Replace an array field value with MongoDB?

To replace an array field value in MongoDB, use the $ positional operator with $set. The positional operator identifies the array element that matches the query condition and replaces it with the new value.

Syntax

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

Sample Data

db.replaceAnArrayFieldValueDemo.insertOne({
    "StudentTechnicalSubjects": ["MySQL", "SQL Server", "PL/SQL"]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5cea41e0ef71edecf6a1f68f")
}

View Current Document

db.replaceAnArrayFieldValueDemo.find().pretty();
{
    "_id": ObjectId("5cea41e0ef71edecf6a1f68f"),
    "StudentTechnicalSubjects": [
        "MySQL",
        "SQL Server",
        "PL/SQL"
    ]
}

Replace Array Element

Replace "SQL Server" with "MongoDB" using the positional operator ?

db.replaceAnArrayFieldValueDemo.update(
    { "StudentTechnicalSubjects": "SQL Server" },
    { $set: { "StudentTechnicalSubjects.$": "MongoDB" } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })

Verify Result

db.replaceAnArrayFieldValueDemo.find().pretty();
{
    "_id": ObjectId("5cea41e0ef71edecf6a1f68f"),
    "StudentTechnicalSubjects": [
        "MySQL",
        "MongoDB",
        "PL/SQL"
    ]
}

Key Points

  • The $ operator matches the first array element that satisfies the query condition.
  • Use $set with arrayField.$ to replace the matched element's value.
  • The query condition must match the exact value you want to replace.

Conclusion

The positional operator $ combined with $set provides an efficient way to replace specific values within MongoDB arrays. This approach maintains array structure while updating only the targeted element.

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

357 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements