Removing an array element from a MongoDB collection

MongoDBDatabaseBig Data Analytics

To remove an array element, simply use $pull along with update(). Let us create a collection with documents −

> db.demo146.insertOne({"ListOfEmployeeNames":["Chris","David","Bob","Mike"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e32f54ffdf09dd6d08539bd")
}

Display all documents from a collection with the help of find() method −

> db.demo146.find();

This will produce the following output −

{ "_id" : ObjectId("5e32f54ffdf09dd6d08539bd"), "ListOfEmployeeNames" : [ "Chris", "David", "Bob", "Mike" ] }

Following is the query to remove an array element from MongoDB −

> db.demo146.update({}, { "$pull": { "ListOfEmployeeNames": "Bob" } });
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Display all documents from a collection with the help of find() method −

> db.demo146.find();

This will produce the following output −

{ "_id" : ObjectId("5e32f54ffdf09dd6d08539bd"), "ListOfEmployeeNames" : [ "Chris", "David", "Mike" ] }
raja
Published on 31-Mar-2020 12:46:47
Advertisements