To delete array values, use $pull in MongoDB. The $pull operator removes from an existing array all instances of a value or values that match a specified condition.
Let us first create a collection with documents −
> db.demo535.insertOne(
... {
...
... "studentId" : "101",
... "studentName" : "Chris",
... "ListOfMailIds" : [
... "[email protected]",
... "[email protected]"
... ]
...
... }
... )
{
"acknowledged" : true,
"insertedId" : ObjectId("5e8c82bfef4dcbee04fbbc00")
}Display all documents from a collection with the help of find() method −
> db.demo535.find();
This will produce the following output −
{ "_id" : ObjectId("5e8c82bfef4dcbee04fbbc00"), "studentId" : "101", "studentName" : "Chris",
"ListOfMailIds" : [ "[email protected]", "[email protected]" ] }Following is the query to delete array value from a document in MongoDB −
> db.demo535.update(
... { _id: ObjectId("5e8c82bfef4dcbee04fbbc00") },
... { $pull: { 'ListOfMailIds': '[email protected]' } }
... );
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })Display all documents from a collection with the help of find() method −
> db.demo535.find();
This will produce the following output −
{ "_id" : ObjectId("5e8c82bfef4dcbee04fbbc00"), "studentId" : "101", "studentName" : "Chris", "ListOfMailIds" : [ "[email protected]" ] }