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
Opposite of addToSet to 'removeFromSet' in MongoDB?
To get the opposite of $addToSet (which adds elements to arrays without duplicates), use the $pull operator. The $pull operator removes all instances of a value from an existing array, effectively working as a "removeFromSet" operation.
Syntax
db.collection.update(
{ matchCriteria },
{ $pull: { "arrayField": "valueToRemove" } }
);
Sample Data
db.oppositeAddToSetDemo.insertMany([
{
"StudentName": "John",
"StudentHobby": ["Cricket", "Cooking", "Drawing"]
},
{
"StudentName": "Carol",
"StudentHobby": ["Cricket", "Dance", "Hiking"]
},
{
"StudentName": "David",
"StudentHobby": ["Learning", "Photography"]
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5c8eddcc2f684a30fbdfd588"),
ObjectId("5c8eddfd2f684a30fbdfd589"),
ObjectId("5c8ede272f684a30fbdfd58a")
]
}
Example: Remove Element Using $pull
Let's remove "Cooking" from John's hobbies using the $pull operator ?
db.oppositeAddToSetDemo.update(
{ "StudentName": "John" },
{ $pull: { "StudentHobby": "Cooking" } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })
Verify Result
db.oppositeAddToSetDemo.find().pretty();
{
"_id": ObjectId("5c8eddcc2f684a30fbdfd588"),
"StudentName": "John",
"StudentHobby": [
"Cricket",
"Drawing"
]
}
{
"_id": ObjectId("5c8eddfd2f684a30fbdfd589"),
"StudentName": "Carol",
"StudentHobby": [
"Cricket",
"Dance",
"Hiking"
]
}
{
"_id": ObjectId("5c8ede272f684a30fbdfd58a"),
"StudentName": "David",
"StudentHobby": [
"Learning",
"Photography"
]
}
Key Points
-
$addToSetadds unique elements to arrays -
$pullremoves all matching elements from arrays -
$pullremoves all instances of the specified value, not just one
Conclusion
The $pull operator serves as the opposite of $addToSet, effectively providing "removeFromSet" functionality. Use $pull to remove specific values from array fields in your MongoDB documents.
Advertisements
