Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to delete element from an array in MongoDB?
To delete element from an array in MongoDB, use the $pull operator. This operator removes all instances of a specified value from an array field.
Syntax
db.collection.update(
{ query },
{ $pull: { arrayField: valueToRemove } },
{ multi: true }
);
Create Sample Data
Let us create a collection with documents −
db.demo279.insertMany([
{ id: [101, 103, 105, 110] },
{ id: [107, 111, 110] }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e490af7dd099650a5401a58"),
ObjectId("5e490b06dd099650a5401a59")
]
}
Display all documents from the collection −
db.demo279.find();
{ "_id": ObjectId("5e490af7dd099650a5401a58"), "id": [101, 103, 105, 110] }
{ "_id": ObjectId("5e490b06dd099650a5401a59"), "id": [107, 111, 110] }
Example: Remove Element from Array
Following is the query to delete element 110 from all arrays −
db.demo279.update(
{},
{ $pull: { id: 110 } },
{ multi: true }
);
WriteResult({ "nMatched": 2, "nUpserted": 0, "nModified": 2 })
Verify Result
Display all documents to verify the deletion −
db.demo279.find();
{ "_id": ObjectId("5e490af7dd099650a5401a58"), "id": [101, 103, 105] }
{ "_id": ObjectId("5e490b06dd099650a5401a59"), "id": [107, 111] }
Key Points
-
$pullremoves all instances of the specified value from the array - Use
multi: trueto update multiple documents - The operator works on all array elements that match the specified value
Conclusion
The $pull operator efficiently removes specific values from arrays across multiple documents. Use multi: true to apply the deletion to all matching documents in the collection.
Advertisements
