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
MongoDB query to remove element from array as sub property
To remove an element from an array that exists as a sub-property in MongoDB, use the $pull operator with dot notation to target the nested array field.
Syntax
db.collection.update(
{ "matchField": "matchValue" },
{ "$pull": { "parentField.arrayField": { "field": "valueToRemove" } } }
);
Sample Data
Let us first create a collection with documents ?
db.demo388.insertOne({
_id: '101',
userDetails: {
isMarried: false,
userInfo: [
{
Name: "Chris",
Age: 21
}
]
}
});
{ "acknowledged" : true, "insertedId" : "101" }
Display all documents from a collection with the help of find() method ?
db.demo388.find();
{ "_id" : "101", "userDetails" : { "isMarried" : false, "userInfo" : [ { "Name" : "Chris", "Age" : 21 } ] } }
Example: Remove Element from Nested Array
Following is the query to remove element from array as sub property ?
db.demo388.update(
{ "_id": "101" },
{ "$pull": { "userDetails.userInfo": { "Name": "Chris" } } }
);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Verify Result
Display all documents from a collection with the help of find() method ?
db.demo388.find();
{ "_id" : "101", "userDetails" : { "isMarried" : false, "userInfo" : [ ] } }
Conclusion
Use $pull with dot notation to remove elements from nested arrays. The operator matches and removes all array elements that satisfy the specified condition, leaving an empty array if all elements are removed.
Advertisements
