MongoDB query to update tag

To update a specific tag in a MongoDB array, use the $ positional operator with the $set modifier. This allows you to match and update a specific element within an array based on a query condition.

Syntax

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

Sample Data

Let us create a collection with documents containing tags ?

db.demo713.insertOne({
    tags: [
        {
            id: 101,
            Name: "Tag-1"
        },
        {
            id: 102,
            Name: "Tag-3"
        },
        {
            id: 103,
            Name: "Tag-3"
        }
    ]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5ea8625a5d33e20ed1097b87")
}

Display all documents from the collection ?

db.demo713.find();
{
    "_id": ObjectId("5ea8625a5d33e20ed1097b87"),
    "tags": [
        { "id": 101, "Name": "Tag-1" },
        { "id": 102, "Name": "Tag-3" },
        { "id": 103, "Name": "Tag-3" }
    ]
}

Example: Update Specific Tag

Update the tag with id 102 from "Tag-3" to "Tag-2" ?

db.demo713.update(
    { "tags.id": 102 },
    { $set: { "tags.$.Name": "Tag-2" } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })

Verify Result

Display the updated document ?

db.demo713.find().pretty();
{
    "_id": ObjectId("5ea8625a5d33e20ed1097b87"),
    "tags": [
        {
            "id": 101,
            "Name": "Tag-1"
        },
        {
            "id": 102,
            "Name": "Tag-2"
        },
        {
            "id": 103,
            "Name": "Tag-3"
        }
    ]
}

Key Points

  • The $ positional operator identifies the first array element that matches the query condition.
  • Use dot notation to specify which field within the matched array element to update.
  • Only the first matching element in the array will be updated.

Conclusion

The positional operator $ combined with $set provides an efficient way to update specific elements in MongoDB arrays. This approach ensures precise updates without affecting other array elements.

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

295 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements