0
0
MongodbHow-ToBeginner · 3 min read

How to Remove Element from Array in MongoDB: Simple Guide

To remove an element from an array in MongoDB, use the $pull update operator. It removes all instances of a specified value or condition from the array field in your documents.
📐

Syntax

The $pull operator removes elements from an array that match a specified condition.

  • { $pull: { field: valueOrCondition } }: Removes elements equal to valueOrCondition from the array in field.
  • field: The name of the array field to update.
  • valueOrCondition: The value or query condition to match elements to remove.
mongodb
db.collection.updateOne(
  { _id: documentId },
  { $pull: { arrayField: valueOrCondition } }
)
💻

Example

This example removes the number 3 from the numbers array in a document.

mongodb
db.test.updateOne(
  { _id: 1 },
  { $pull: { numbers: 3 } }
)

// Before update:
// { _id: 1, numbers: [1, 2, 3, 4, 3] }

// After update:
// { _id: 1, numbers: [1, 2, 4] }
Output
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
⚠️

Common Pitfalls

Common mistakes when removing elements from arrays include:

  • Using $pull with a value that does not exist, which results in no change.
  • Confusing $pull with $pop, which removes the first or last element regardless of value.
  • Not specifying the correct field name or condition, so no elements are removed.

Always verify the array field and the value or condition you want to remove.

mongodb
/* Wrong: Using $pop instead of $pull to remove specific value */
db.test.updateOne(
  { _id: 1 },
  { $pop: { numbers: 3 } } // Incorrect usage
)

/* Right: Use $pull to remove all 3s */
db.test.updateOne(
  { _id: 1 },
  { $pull: { numbers: 3 } }
)
📊

Quick Reference

OperatorPurposeExample
$pullRemove elements matching condition from array{ $pull: { tags: 'mongodb' } }
$popRemove first (-1) or last (1) element from array{ $pop: { tags: 1 } }
$pullAllRemove all specified values from array{ $pullAll: { tags: ['mongodb', 'database'] } }

Key Takeaways

Use the $pull operator to remove specific elements from an array in MongoDB.
$pull removes all matching elements, not just the first one.
Do not confuse $pull with $pop; $pop removes elements by position, not value.
Always specify the correct array field and matching condition for $pull.
If no elements match, $pull makes no changes but does not cause errors.