Removing an array element from MongoDB collection using update() and $pull

To remove a specific element from an array in MongoDB, use the $pull operator with the update() method. This operator removes all instances of a value that match the specified condition from an array field.

Syntax

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

Create Sample Data

Let us first create a collection with documents ?

db.removingAnArrayElementDemo.insertOne({
    "UserMessage": ["Hi", "Hello", "Bye"]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5cef97bdef71edecf6a1f6a4")
}

Display all documents from a collection with the help of find() method ?

db.removingAnArrayElementDemo.find().pretty();
{
    "_id": ObjectId("5cef97bdef71edecf6a1f6a4"),
    "UserMessage": [
        "Hi",
        "Hello",
        "Bye"
    ]
}

Example: Remove Array Element

Following is the query to remove an array element from MongoDB ?

db.removingAnArrayElementDemo.update(
    { _id: ObjectId("5cef97bdef71edecf6a1f6a4") },
    { $pull: { "UserMessage": "Hello" } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })

Verify Result

Let us check the document once again ?

db.removingAnArrayElementDemo.find().pretty();
{
    "_id": ObjectId("5cef97bdef71edecf6a1f6a4"),
    "UserMessage": [
        "Hi",
        "Bye"
    ]
}

Conclusion

The $pull operator successfully removes all matching elements from an array field. This operation modifies the document in place and is useful for cleaning up array data in MongoDB collections.

Updated on: 2026-03-15T01:26:19+05:30

229 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements