Make MongoDB replace single array value with string?

To replace a single array value with a string in MongoDB, use the $set operator combined with the positional operator $. The positional operator identifies the array element that matches the query condition and allows you to update it.

Syntax

db.collection.updateMany(
    { "arrayField": "valueToMatch" },
    { "$set": { "arrayField.$": "newValue" } }
);

Sample Data

db.demo564.insertOne({
    "StudentName": ["Chris", "David", "Mike", "Sam"]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5e90880a39cfeaaf0b97b576")
}

Display all documents from the collection ?

db.demo564.find().pretty();
{
    "_id": ObjectId("5e90880a39cfeaaf0b97b576"),
    "StudentName": [
        "Chris",
        "David",
        "Mike",
        "Sam"
    ]
}

Example: Replace Array Value

Replace "David" with "Carol Taylor" in the StudentName array ?

db.demo564.updateMany(
    { "StudentName": "David" },
    { "$set": { "StudentName.$": "Carol Taylor" } }
);
{
    "acknowledged": true,
    "matchedCount": 1,
    "modifiedCount": 1
}

Verify Result

db.demo564.find().pretty();
{
    "_id": ObjectId("5e90880a39cfeaaf0b97b576"),
    "StudentName": [
        "Chris",
        "Carol Taylor",
        "Mike",
        "Sam"
    ]
}

Key Points

  • The $ positional operator matches the first array element that satisfies the query condition.
  • Use updateMany() to update all matching documents or updateOne() for a single document.
  • The query condition must match the exact value you want to replace.

Conclusion

The positional operator $ with $set provides an efficient way to replace specific array values. This method updates only the matched element while preserving the array structure and other elements.

Updated on: 2026-03-15T03:35:39+05:30

753 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements