MongoDB pull with positional operator?


Use $pull operator along with positional operator($) in MongoDB. Let us first create a collection with documents −

> db.pullWithPositionalOperatorDemo.insertOne(
...   {
...      _id: 100,
...      "StudentDetails": [
...         {
...            "StudentId": "STU-1",
...            "StudentFavouriteSubject": ["MongoDB", "Java"]
...         },
...         {
...            "StudentId": "STU-2",
...            "StudentFavouriteSubject": ["PHP", "MySQL"]
...         }
...      ]
...   }
... );
{ "acknowledged" : true, "insertedId" : 100 }

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

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

This will produce the following output −

{
   "_id" : 100,
   "StudentDetails" : [
      {
         "StudentId" : "STU-1",
         "StudentFavouriteSubject" : [
            "MongoDB",
            "Java"
         ]
      },
      {
         "StudentId" : "STU-2",
         "StudentFavouriteSubject" : [
            "PHP",
            "MySQL"
         ]
      }
   ]
}

Following is the query to perform pull with positional operator −

> db.pullWithPositionalOperatorDemo.update({
...   "StudentDetails" : {
...      "$elemMatch" : {
...         "StudentId" : "STU-2",
...         "StudentFavouriteSubject" : "MySQL"
...      }
...   }
... }, {
...      $pull : {
...         "StudentDetails.$.StudentFavouriteSubject" : "MySQL"
...      }
... }, {
...    multi : true
... });
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Let us check all documents from the above collection once again −

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

This will produce the following output −

{
   "_id" : 100,
   "StudentDetails" : [
      {
         "StudentId" : "STU-1",
         "StudentFavouriteSubject" : [
            "MongoDB",
            "Java"
         ]
      },
      {
         "StudentId" : "STU-2",
         "StudentFavouriteSubject" : [
            "PHP"
         ]
      }
   ]
}

Updated on: 30-Jul-2019

83 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements