Remove and update the existing record in MongoDB?

To remove and update existing records in MongoDB, use the $pull operator which removes elements from an array that match specified criteria. This operator effectively updates the document by removing the matching array elements.

Syntax

db.collection.update(
    { "filter_condition": "value" },
    { "$pull": { "arrayField": { "field": "valueToRemove" } } }
);

Sample Data

Let us create a collection with documents containing user details in an array ?

db.removeDemo.insertMany([
    {
        "UserName": "Larry",
        "UserDetails": [
            {
                "_id": 101,
                "UserEmailId": "976Larry@gmail.com"
            }
        ]
    },
    {
        "UserName": "Mike",
        "UserDetails": [
            {
                "_id": 102,
                "UserEmailId": "Mike121@gmail.com"
            }
        ]
    }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5cc7f9f88f9e6ff3eb0ce446"),
        ObjectId("5cc7f9f98f9e6ff3eb0ce447")
    ]
}

Display Current Documents

db.removeDemo.find().pretty();
{
    "_id": ObjectId("5cc7f9f88f9e6ff3eb0ce446"),
    "UserName": "Larry",
    "UserDetails": [
        {
            "_id": 101,
            "UserEmailId": "976Larry@gmail.com"
        }
    ]
}
{
    "_id": ObjectId("5cc7f9f98f9e6ff3eb0ce447"),
    "UserName": "Mike",
    "UserDetails": [
        {
            "_id": 102,
            "UserEmailId": "Mike121@gmail.com"
        }
    ]
}

Example: Remove Array Element Using $pull

Remove the UserDetails element with _id 102 from Mike's document ?

db.removeDemo.update(
    {"_id": ObjectId("5cc7f9f98f9e6ff3eb0ce447")},
    { "$pull": { "UserDetails": {"_id": 102}}}
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })

Verify Result

db.removeDemo.find().pretty();
{
    "_id": ObjectId("5cc7f9f88f9e6ff3eb0ce446"),
    "UserName": "Larry",
    "UserDetails": [
        {
            "_id": 101,
            "UserEmailId": "976Larry@gmail.com"
        }
    ]
}
{
    "_id": ObjectId("5cc7f9f98f9e6ff3eb0ce447"),
    "UserName": "Mike",
    "UserDetails": []
}

Key Points

  • $pull removes all array elements that match the specified condition
  • The document structure remains intact; only matching array elements are removed
  • If all elements are removed, the array becomes empty but still exists

Conclusion

The $pull operator efficiently removes specific elements from arrays while updating the document in place. This approach maintains document structure and provides precise control over array element removal.

Updated on: 2026-03-15T00:56:33+05:30

196 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements