Update a specific MongoDB document in array with set and positional operator?

To update a specific document in an array, use MongoDB's $set operator with the positional $ operator. The $ operator identifies the matched array element, while $set modifies the specified field within that element.

Syntax

db.collection.updateOne(
    { "arrayField.fieldName": "matchValue" },
    { $set: { "arrayField.$.fieldToUpdate": "newValue" } }
);

Sample Data

Let us create a collection with documents ?

db.demo462.insertOne({
    "id": 1,
    "DueDateDetails": [
        {
            "Name": "David",
            "Age": 21,
            "CountryName": ["US", "UK"]
        },
        {
            "Name": "Chris",
            "Age": 23,
            "CountryName": ["UK"]
        }
    ]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5e7f6c59cb66ccba22cc9dce")
}

Display all documents from the collection ?

db.demo462.find().pretty();
{
    "_id": ObjectId("5e7f6c59cb66ccba22cc9dce"),
    "id": 1,
    "DueDateDetails": [
        {
            "Name": "David",
            "Age": 21,
            "CountryName": ["US", "UK"]
        },
        {
            "Name": "Chris",
            "Age": 23,
            "CountryName": ["UK"]
        }
    ]
}

Example: Update Array Element with $set and Positional $

Update Chris's CountryName field to "AUS" ?

db.demo462.updateOne(
    { id: 1, "DueDateDetails.Name": "Chris" },
    { $set: { "DueDateDetails.$.CountryName": "AUS" } }
);
{ "acknowledged": true, "matchedCount": 1, "modifiedCount": 1 }

Verify Result

Display the updated document ?

db.demo462.find().pretty();
{
    "_id": ObjectId("5e7f6c59cb66ccba22cc9dce"),
    "id": 1,
    "DueDateDetails": [
        {
            "Name": "David",
            "Age": 21,
            "CountryName": ["US", "UK"]
        },
        {
            "Name": "Chris",
            "Age": 23,
            "CountryName": "AUS"
        }
    ]
}

Key Points

  • The $ operator matches the first array element that satisfies the query condition.
  • $set replaces the entire field value ? Chris's CountryName changed from an array to a string.
  • Use dot notation "arrayField.$.fieldName" to target specific fields within matched array elements.

Conclusion

The combination of $set and positional $ operator provides precise control for updating specific documents within MongoDB arrays. The $ identifies the matched element, while $set modifies the target field.

Updated on: 2026-03-15T03:03:53+05:30

326 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements