Tutorialspoint

1 Answer
Anvi Jain

Use the $pull to remove array elements from a MongoDB document as shown in the following syntax −

db.yourCollectionName.update( { },{ $pull: { yourFieldName: yourValue }},{multi:true });

Let us first create a collection with documents −

>db.removeArrayElementsDemo.insertOne({"AllPlayerName":["John","Sam","Carol","David"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd90d011a844af18acdffc1")
}
>db.removeArrayElementsDemo.insertOne({"AllPlayerName":["Chris","Robert","John","Mike"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd90d2e1a844af18acdffc2")
}

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

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

This will produce the following output −

{
   "_id" : ObjectId("5cd90d011a844af18acdffc1"),
   "AllPlayerName" : [
      "John",
      "Sam",
      "Carol",
      "David"
   ]
}
{
   "_id" : ObjectId("5cd90d2e1a844af18acdffc2"),
   "AllPlayerName" : [
      "Chris",
      "Robert",
      "John",
      "Mike"
   ]
}

Here is the query to remove array elements from a document −

> db.removeArrayElementsDemo.update( { },{ $pull: { AllPlayerName: "John" }},{multi:true });
WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })

Let us check all the documents once again −

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

This will produce the following output −

{
   "_id" : ObjectId("5cd90d011a844af18acdffc1"),
   "AllPlayerName" : [
      "Sam",
      "Carol",
      "David"
   ]
}
{
   "_id" : ObjectId("5cd90d2e1a844af18acdffc2"),
   "AllPlayerName" : [
      "Chris",
      "Robert",
      "Mike"
   ]
}

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.