Pull and add to set at the same time with MongoDB? Is it Possible?

Yes, you can use pull and add operations simultaneously in MongoDB using $addToSet and $pull operators with bulk operations. This allows you to modify arrays in multiple ways within a single database round trip.

Syntax

var bulkOp = db.collection.initializeOrderedBulkOp();
bulkOp.find({condition1}).updateOne({$addToSet: {arrayField: newValue}});
bulkOp.find({condition2}).updateOne({$pull: {arrayField: valueToRemove}});
bulkOp.execute();

Sample Data

db.pullAndAddToSetDemo.insertOne({StudentScores: [78, 89, 90]});
{
    "acknowledged": true,
    "insertedId": ObjectId("5c9a797e15e86fd1496b38af")
}

Let's view the initial document ?

db.pullAndAddToSetDemo.find().pretty();
{
    "_id": ObjectId("5c9a797e15e86fd1496b38af"),
    "StudentScores": [
        78,
        89,
        90
    ]
}

Example: Pull and Add Simultaneously

Remove score 90 and add score 99 in the same operation ?

var addAndPull = db.pullAndAddToSetDemo.initializeOrderedBulkOp();
addAndPull.find({"StudentScores": 89}).updateOne({"$addToSet": {"StudentScores": 99}});
addAndPull.find({"StudentScores": 90}).updateOne({"$pull": {"StudentScores": 90}});
addAndPull.execute();
BulkWriteResult({
    "writeErrors": [],
    "writeConcernErrors": [],
    "nInserted": 0,
    "nUpserted": 0,
    "nMatched": 2,
    "nModified": 2,
    "nRemoved": 0,
    "upserted": []
})

Verify Result

db.pullAndAddToSetDemo.find().pretty();
{
    "_id": ObjectId("5c9a797e15e86fd1496b38af"),
    "StudentScores": [
        78,
        89,
        99
    ]
}

How It Works

  • initializeOrderedBulkOp() creates a bulk operation that executes commands in sequence
  • $addToSet adds 99 to the array (only if it doesn't already exist)
  • $pull removes all instances of 90 from the array
  • execute() runs both operations in a single database round trip

Conclusion

MongoDB bulk operations enable simultaneous pull and add operations on arrays. This approach is efficient as it combines multiple array modifications into a single database transaction, reducing network overhead.

Updated on: 2026-03-15T00:30:32+05:30

904 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements