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

  • $addToSet adds unique elements to arrays
  • $pull removes all matching elements from arrays
  • $pull removes 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.

Updated on: 2026-03-15T00:14:35+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements