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


Yes, you can use pull and add at the same time with $addToSet and $pull operator. Let us first create a collection with documents

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

Following is the query to display all documents from a collection with the help of find() method

> db.pullAndAddToSetDemo.find().pretty();

This will produce the following output

{
   "_id" : ObjectId("5c9a797e15e86fd1496b38af"),
   "StudentScores" : [
      78,
      89,
      90
   ]
}

Following is the query to pull and addtoset at the same time in MongoDB

> var addAndPull = db.pullAndAddToSetDemo.initializeOrderedBulkOp();
> addAndPull.find({ "StudentScores": 89 }).updateOne({ "$addToSet": { "StudentScores": 99 } });
> addAndPull.find({ "StudentScores": 90 }).updateOne({ "$pull": { "StudentScores": 90 } });
> addAndPull.execute();

This will produce the following output

BulkWriteResult({
   "writeErrors" : [ ],
   "writeConcernErrors" : [ ],
   "nInserted" : 0,
   "nUpserted" : 0,
   "nMatched" : 2,
   "nModified" : 2,
   "nRemoved" : 0,
   "upserted" : [ ]
})

Let us check the document once again from the collection. Following is the query

> db.pullAndAddToSetDemo.find().pretty();

This will produce the following output

{
   "_id" : ObjectId("5c9a797e15e86fd1496b38af"),
   "StudentScores" : [
      78,
      89,
      99
   ]
}

Updated on: 30-Jul-2019

579 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements