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
Removing an array element from MongoDB collection using update() and $pull
To remove a specific element from an array in MongoDB, use the $pull operator with the update() method. This operator removes all instances of a value that match the specified condition from an array field.
Syntax
db.collection.update(
{ query },
{ $pull: { "arrayField": "valueToRemove" } }
);
Create Sample Data
Let us first create a collection with documents ?
db.removingAnArrayElementDemo.insertOne({
"UserMessage": ["Hi", "Hello", "Bye"]
});
{
"acknowledged": true,
"insertedId": ObjectId("5cef97bdef71edecf6a1f6a4")
}
Display all documents from a collection with the help of find() method ?
db.removingAnArrayElementDemo.find().pretty();
{
"_id": ObjectId("5cef97bdef71edecf6a1f6a4"),
"UserMessage": [
"Hi",
"Hello",
"Bye"
]
}
Example: Remove Array Element
Following is the query to remove an array element from MongoDB ?
db.removingAnArrayElementDemo.update(
{ _id: ObjectId("5cef97bdef71edecf6a1f6a4") },
{ $pull: { "UserMessage": "Hello" } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Verify Result
Let us check the document once again ?
db.removingAnArrayElementDemo.find().pretty();
{
"_id": ObjectId("5cef97bdef71edecf6a1f6a4"),
"UserMessage": [
"Hi",
"Bye"
]
}
Conclusion
The $pull operator successfully removes all matching elements from an array field. This operation modifies the document in place and is useful for cleaning up array data in MongoDB collections.
Advertisements
