MongoDB query to match and remove element from an array?



To match and remove element(s) , use MongoDB $pullAll. Let us first create a collection with documents −

> db.removeElementsDemo.insertOne({"ListOfNames":["Mike","Sam","David","Carol"]}); {    "acknowledged" : true,    "insertedId" : ObjectId("5e071e5a25ddae1f53b62203") }

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

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

This will produce the following output −

{    "_id" : ObjectId("5e071e5a25ddae1f53b62203"),       "ListOfNames" : [          "Mike",          "Sam",          "David",          "Carol"    ] }

Here is the query to match and remove element(s) from an array −

> db.removeElementsDemo.update( ... { }, ... { ...    $pullAll: ...    { ...       "ListOfNames": ["Carol"] ...    } ... } ... ); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

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

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

This will produce the following output. Above, we removed only a single value −

{    "_id" : ObjectId("5e071e5a25ddae1f53b62203"),    "ListOfNames" : [       "Mike",       "Sam",       "David"    ] }
Updated on: 2020-03-31T08:04:39+05:30

461 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements