Pull multiple objects from an array in MongoDB?


To pull multiple objects from an array, you can use $pull operator. Let us first create a collection with documents −

> db.pullMultipleObjectsDemo.insertOne(
...    {
...       "ClientId" : "100",
...       "ClientName" : "John",
...       "ClientPersonalDetails" : [
...          {
...             "ClientCountryName" : "US",
...             "ClientProjectName" : "Online Book Store",
...
...          },
...          {
...             "ClientCountryName" : "AUS",
...             "ClientProjectName" : "Online Fee Management",
...
...          },
...          {
...             "ClientCountryName" : "UK",
...             "ClientProjectName" : "Online Pig Dice Game",
...
...          },
...          {
...             "ClientCountryName" : "ANGOLA",
...             "ClientProjectName" : "Online Hospital Management",
...
...          }
...       ]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cc7d0748f9e6ff3eb0ce43d")
}

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

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

This will produce the following output −

{
   "_id" : ObjectId("5cc7d0748f9e6ff3eb0ce43d"),
   "ClientId" : "100",
   "ClientName" : "John",
   "ClientPersonalDetails" : [
      {
         "ClientCountryName" : "US",
         "ClientProjectName" : "Online Book Store"
      },
      {
         "ClientCountryName" : "AUS",
         "ClientProjectName" : "Online Fee Management"
      },
      {
         "ClientCountryName" : "UK",
         "ClientProjectName" : "Online Pig Dice Game"
      },
      {
         "ClientCountryName" : "ANGOLA",
         "ClientProjectName" : "Online Hospital Management"
      }
   ]
}

Following is the query to pull multiple objects from an array −

> db.pullMultipleObjectsDemo.update(
...    {"_id": ObjectId("5cc7d0748f9e6ff3eb0ce43d")},
...    {"$pull":{"ClientPersonalDetails":{"ClientProjectName":{$in:["Online Book Store","Online Pig Dice Game"]}}}}
... );
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Let us display all documents from the collection in order to check the objects have been removed from an array or not. The query is as follows −

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

This will produce the following output −

{
   "_id" : ObjectId("5cc7d0748f9e6ff3eb0ce43d"),
   "ClientId" : "100",
   "ClientName" : "John",
   "ClientPersonalDetails" : [
      {
         "ClientCountryName" : "AUS",
         "ClientProjectName" : "Online Fee Management"
      },
      {
         "ClientCountryName" : "ANGOLA",
         "ClientProjectName" : "Online Hospital Management"
      }
   ]
}

Look at the above sample output, the multiple objects have been removed from the array.

Updated on: 30-Jul-2019

758 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements