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 pull an array element (which is a document) in MongoDB?
To pull (remove) an array element that is a document in MongoDB, use the $pull operator with specific field conditions to match and remove the target document from the array.
Syntax
db.collection.update(
{ query },
{ $pull: { "arrayField": { "field": "value" } } }
);
Sample Data
db.pullAnArrayElementDemo.insertOne({
"StudentDetails": [
{
"StudentFirstName": "Chris",
"StudentScore": 56
},
{
"StudentFirstName": "Robert",
"StudentScore": 59
}
]
});
{
"acknowledged": true,
"insertedId": ObjectId("5cd3b55bedc6604c74817cd5")
}
Example: Remove Document by Field Match
Let's view the initial data ?
db.pullAnArrayElementDemo.find().pretty();
{
"_id": ObjectId("5cd3b55bedc6604c74817cd5"),
"StudentDetails": [
{
"StudentFirstName": "Chris",
"StudentScore": 56
},
{
"StudentFirstName": "Robert",
"StudentScore": 59
}
]
}
Now remove the document where StudentFirstName is "Chris" ?
db.pullAnArrayElementDemo.update(
{},
{ $pull: { "StudentDetails": { "StudentFirstName": "Chris" } } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Verify Result
db.pullAnArrayElementDemo.find().pretty();
{
"_id": ObjectId("5cd3b55bedc6604c74817cd5"),
"StudentDetails": [
{
"StudentFirstName": "Robert",
"StudentScore": 59
}
]
}
Conclusion
The $pull operator removes all array elements that match the specified condition. It's ideal for removing document objects from arrays based on field values, providing precise control over array modifications.
Advertisements
