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 pull with positional operator?
The $pull operator combined with the positional operator ($) in MongoDB allows you to remove specific values from arrays within nested documents. Use $elemMatch to identify the target document and $ to reference the matched array element.
Syntax
db.collection.update(
{
"arrayField": {
"$elemMatch": {
"field": "matchValue"
}
}
},
{
"$pull": {
"arrayField.$.nestedArray": "valueToRemove"
}
}
);
Sample Data
db.pullWithPositionalOperatorDemo.insertOne({
_id: 100,
"StudentDetails": [
{
"StudentId": "STU-1",
"StudentFavouriteSubject": ["MongoDB", "Java"]
},
{
"StudentId": "STU-2",
"StudentFavouriteSubject": ["PHP", "MySQL"]
}
]
});
{ "acknowledged": true, "insertedId": 100 }
Example: Remove Subject from Specific Student
Let's remove "MySQL" from STU-2's favourite subjects ?
db.pullWithPositionalOperatorDemo.update(
{
"StudentDetails": {
"$elemMatch": {
"StudentId": "STU-2",
"StudentFavouriteSubject": "MySQL"
}
}
},
{
"$pull": {
"StudentDetails.$.StudentFavouriteSubject": "MySQL"
}
}
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Verify Result
db.pullWithPositionalOperatorDemo.find().pretty();
{
"_id": 100,
"StudentDetails": [
{
"StudentId": "STU-1",
"StudentFavouriteSubject": [
"MongoDB",
"Java"
]
},
{
"StudentId": "STU-2",
"StudentFavouriteSubject": [
"PHP"
]
}
]
}
Key Points
-
$elemMatchidentifies the specific array element that matches multiple conditions -
$references the first matched element from the query condition -
$pullremoves all instances of the specified value from the target array
Conclusion
Combining $pull with the positional operator enables precise removal of values from nested arrays. Use $elemMatch to match the target document and $ to reference the matched element position.
Advertisements
