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

MongoDBDatabaseBig Data Analytics

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" ] }
raja
Published on 14-May-2020 06:32:54
Advertisements