Unset an attribute from a single array element in MongoDB?

To unset an attribute from a single array element in MongoDB, use the $unset operator combined with the $ positional operator to target the specific array element that matches your query condition.

Syntax

db.collection.update(
    {"arrayField.attribute": "matchValue"},
    {$unset: {"arrayField.$.attribute": 1}}
)

Create Sample Data

db.unsetAnAttributeDemo.insertOne({
    _id: 1,
    "StudentDetails": [
        {
            "StudentFirstName": "Ramit",
            "StudentCountryName": "UK"
        },
        {
            "StudentFirstName": "Bob",
            "StudentCountryName": "US"
        },
        {
            "StudentFirstName": "Carol",
            "StudentCountryName": "AUS"
        }
    ]
})
{ "acknowledged": true, "insertedId": 1 }

View Initial Data

db.unsetAnAttributeDemo.find().pretty()
{
    "_id": 1,
    "StudentDetails": [
        {
            "StudentFirstName": "Ramit",
            "StudentCountryName": "UK"
        },
        {
            "StudentFirstName": "Bob",
            "StudentCountryName": "US"
        },
        {
            "StudentFirstName": "Carol",
            "StudentCountryName": "AUS"
        }
    ]
}

Unset Attribute from Specific Array Element

Remove the "StudentCountryName" attribute from the student with country "AUS" ?

db.unsetAnAttributeDemo.update(
    {"StudentDetails.StudentCountryName": "AUS"},
    {$unset: {"StudentDetails.$.StudentCountryName": 1}}
)
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })

Verify Result

db.unsetAnAttributeDemo.find().pretty()
{
    "_id": 1,
    "StudentDetails": [
        {
            "StudentFirstName": "Ramit",
            "StudentCountryName": "UK"
        },
        {
            "StudentFirstName": "Bob",
            "StudentCountryName": "US"
        },
        {
            "StudentFirstName": "Carol"
        }
    ]
}

Conclusion

The $unset operator with $ positional operator removes specific attributes from array elements. The $ identifies the first matching array element, and $unset removes the specified field from that element only.

Updated on: 2026-03-15T00:49:48+05:30

223 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements