MongoDB query to pull array element from a collection?

Use the $pull operator to remove specific values from an array field in MongoDB. The $pull operator removes all instances of a value from an existing array that match a specified condition.

Syntax

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

Sample Data

Let us first create a collection with a document containing an array ?

db.pullElementFromAnArrayDemo.insertOne({
    "StudentScores": [89, 56, 78, 90]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5cd0104a588d4a6447b2e063")
}

Display the document to verify our data ?

db.pullElementFromAnArrayDemo.find();
{ "_id": ObjectId("5cd0104a588d4a6447b2e063"), "StudentScores": [89, 56, 78, 90] }

Example: Pull Array Element

Remove the value 78 from the StudentScores array ?

db.pullElementFromAnArrayDemo.update(
    {},
    { $pull: { StudentScores: 78 } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })

Verify Result

Check the updated document to confirm the element was removed ?

db.pullElementFromAnArrayDemo.find();
{ "_id": ObjectId("5cd0104a588d4a6447b2e063"), "StudentScores": [89, 56, 90] }

Key Points

  • $pull removes all instances of the specified value from the array
  • If the value doesn't exist, the operation completes without error
  • Use an empty query {} to update all documents in the collection

Conclusion

The $pull operator efficiently removes specific values from array fields. It modifies the array in-place and removes all matching occurrences of the specified value.

Updated on: 2026-03-15T01:01:04+05:30

224 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements