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 do I delete array value from a document in MongoDB?
To delete array values from a document in MongoDB, use the $pull operator. The $pull operator removes from an existing array all instances of a value or values that match a specified condition.
Syntax
db.collection.update(
{ "matchCondition": "value" },
{ $pull: { "arrayField": "valueToRemove" } }
);
Create Sample Data
Let us first create a collection with documents ?
db.demo535.insertOne({
"studentId": "101",
"studentName": "Chris",
"ListOfMailIds": [
"Chris@gmail.com",
"Chris@yahoo.com"
]
});
{
"acknowledged": true,
"insertedId": ObjectId("5e8c82bfef4dcbee04fbbc00")
}
Display all documents from a collection with the help of find() method ?
db.demo535.find();
{
"_id": ObjectId("5e8c82bfef4dcbee04fbbc00"),
"studentId": "101",
"studentName": "Chris",
"ListOfMailIds": ["Chris@gmail.com", "Chris@yahoo.com"]
}
Example: Delete Specific Array Value
Following is the query to delete array value from a document in MongoDB ?
db.demo535.update(
{ _id: ObjectId("5e8c82bfef4dcbee04fbbc00") },
{ $pull: { "ListOfMailIds": "Chris@yahoo.com" } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Verify Result
Display all documents to verify the deletion ?
db.demo535.find();
{
"_id": ObjectId("5e8c82bfef4dcbee04fbbc00"),
"studentId": "101",
"studentName": "Chris",
"ListOfMailIds": ["Chris@gmail.com"]
}
Conclusion
The $pull operator efficiently removes specific values from arrays in MongoDB documents. It removes all instances of the matching value and automatically maintains the array structure.
Advertisements
