Opposite of $addToSet to '$removeFromSet' in MongoDB?

MongoDBDatabaseBig Data Analytics

To get the opposite of $addToSet to '$removeFromSet', use the $pull operator.

Let us create a collection with a document. The query to create a collection with a document is as follows −

> db.oppositeAddToSetDemo.insertOne({"StudentName":"John","StudentHobby":["Cricket","Cooking","Drawing"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8eddcc2f684a30fbdfd588")
}
> db.oppositeAddToSetDemo.insertOne({"StudentName":"Carol","StudentHobby":["Cricket","Dance","Hiking"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8eddfd2f684a30fbdfd589")
}
> db.oppositeAddToSetDemo.insertOne({"StudentName":"David","StudentHobby":["Learning","Photography"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c8ede272f684a30fbdfd58a")
}

Display all documents from a collection with the help of find() method. The query is as follows −

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

The following is the output −

{
   "_id" : ObjectId("5c8eddcc2f684a30fbdfd588"),
   "StudentName" : "John",
   "StudentHobby" : [
      "Cricket",
      "Cooking",
      "Drawing"
   ]
}
{
   "_id" : ObjectId("5c8eddfd2f684a30fbdfd589"),
   "StudentName" : "Carol",
   "StudentHobby" : [
      "Cricket",
      "Dance",
      "Hiking"
   ]
}
{
   "_id" : ObjectId("5c8ede272f684a30fbdfd58a"),
   "StudentName" : "David",
   "StudentHobby" : [
      "Learning",
      "Photography"
   ]
}

Here is the query for opposite of $addToSet to '$removeFromSet' using $pull operator −

> db.oppositeAddToSetDemo.update(
... {"StudentName": "John"},
... {$pull: { "StudentHobby": "Cooking"}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Let us check the documents from the collection using find(). The query is as follows:

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

The following is the output −

{
   "_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"
   ]
}
raja
Published on 29-Mar-2019 17:49:36
Advertisements