How do I delete array value from a document in MongoDB?


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" : [
...       "Chris@gmail.com",
...       "Chris@yahoo.com"
...    ]
...
... }
... )
{
   "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" : [ "Chris@gmail.com", "Chris@yahoo.com" ] }

Following is the query to delete array value from a document in MongoDB −

> db.demo535.update(
... { _id: ObjectId("5e8c82bfef4dcbee04fbbc00") },
... { $pull: { 'ListOfMailIds': 'Chris@yahoo.com' } }
... );
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" : [ "Chris@gmail.com" ] }

Updated on: 14-May-2020

349 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements