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
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 -
$addToSetadds 99 to the array (only if it doesn't already exist) -
$pullremoves 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.
Advertisements
