To remove a specific element, use $pull. Let us create a collection with documents −
> db.demo125.insertOne({"ListOfNames":["John","Chris","Bob","David","Carol"]}); { "acknowledged" : true, "insertedId" : ObjectId("5e2f304068e7f832db1a7f55") }
Display all documents from a collection with the help of find() method −
> db.demo125.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5e2f304068e7f832db1a7f55"), "ListOfNames" : [ "John", "Chris", "Bob", "David", "Carol" ] }
Following is the query to remove a specific element from array in MongoDB −
> db.demo125.update( ... { }, ... { $pull: { ListOfNames: { $in: [ "David"] }} }, ... { multi: true } ... ) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo125.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5e2f304068e7f832db1a7f55"), "ListOfNames" : [ "John", "Chris", "Bob", "Carol" ] }