MongoDB query to match and remove element from an array?

MongoDBDatabaseBig Data Analytics

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"
   ]
}
raja
Published on 31-Mar-2020 08:04:11
Advertisements