MongoDB query to pull a specific value from a document

To pull a specific value from a document in MongoDB, use the $pull operator with the update() method. The $pull operator removes all instances of a specified value from an existing array.

Syntax

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

Sample Data

Let us create a collection with documents ?

db.demo318.insertMany([
    { Subject: ["MySQL", "MongoDB", "Java"] },
    { Subject: ["Spring", "Hibernate"] }
])
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e50ea6df8647eb59e562062"),
        ObjectId("5e50ea78f8647eb59e562063")
    ]
}

Display all documents from the collection ?

db.demo318.find()
{ "_id": ObjectId("5e50ea6df8647eb59e562062"), "Subject": ["MySQL", "MongoDB", "Java"] }
{ "_id": ObjectId("5e50ea78f8647eb59e562063"), "Subject": ["Spring", "Hibernate"] }

Example: Pull Specific Value

The following query pulls the specific value "Hibernate" from the Subject array ?

db.demo318.update(
    { Subject: "Hibernate" },
    { $pull: { "Subject": "Hibernate" } }
)
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })

Verify Result

Display all documents to verify the value has been removed ?

db.demo318.find()
{ "_id": ObjectId("5e50ea6df8647eb59e562062"), "Subject": ["MySQL", "MongoDB", "Java"] }
{ "_id": ObjectId("5e50ea78f8647eb59e562063"), "Subject": ["Spring"] }

Conclusion

The $pull operator effectively removes specified values from array fields. It matches documents containing the value and removes all instances of that value from the specified array field.

Updated on: 2026-03-15T02:29:15+05:30

538 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements