How do I remove a string from an array in a MongoDB document?

To remove a string from an array in MongoDB, use the $pull operator. This operator removes all instances of a value or values that match a specified condition from an existing array.

Syntax

db.collection.update(
    { <query> },
    { $pull: { <field>: <value> } }
);

Create Sample Data

Let us first create a collection with documents ?

db.removeAStringDemo.insertOne({
    "Score": [45, 67, 89, "John", 98, 99, 67]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5cda5224b50a6c6dd317adbd")
}

Display all documents from the collection ?

db.removeAStringDemo.find().pretty();
{
    "_id": ObjectId("5cda5224b50a6c6dd317adbd"),
    "Score": [
        45,
        67,
        89,
        "John",
        98,
        99,
        67
    ]
}

Example: Remove String from Array

Remove the string "John" from the Score array ?

db.removeAStringDemo.update(
    { _id: ObjectId("5cda5224b50a6c6dd317adbd") },
    { $pull: { "Score": "John" } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })

Verify Result

Check the document to confirm the string has been removed ?

db.removeAStringDemo.find().pretty();
{
    "_id": ObjectId("5cda5224b50a6c6dd317adbd"),
    "Score": [
        45,
        67,
        89,
        98,
        99,
        67
    ]
}

Conclusion

The $pull operator effectively removes all matching string values from an array. It modifies the existing document by removing the specified value while preserving the array structure and other elements.

Updated on: 2026-03-15T01:23:53+05:30

470 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements