Removing item from array in MongoDB?

MongoDBDatabaseBig Data Analytics

To remove item from array, use $pull in MongoDB. Let us create a collection with documents −

> db.demo224.insertOne({"ListOfTechnology":["Spring","Hibernate","Java"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3ee6d103d395bdc2134733")
}
> db.demo224.insertOne({"ListOfTechnology":["Groovy"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3ee6ec03d395bdc2134734")
}

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

> db.demo224.find();

This will produce the following output −

{ "_id" : ObjectId("5e3ee6d103d395bdc2134733"), "ListOfTechnology" : [ "Spring", "Hibernate", "Java" ] }
{ "_id" : ObjectId("5e3ee6ec03d395bdc2134734"), "ListOfTechnology" : [ "Groovy" ] }

Following is the query to remove item from array in MongoDB −

>db.demo224.update({_id:ObjectId("5e3ee6d103d395bdc2134733")},{$pull:{"ListOfTechnology":"Java"}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

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

> db.demo224.find();

This will produce the following output −

{ "_id" : ObjectId("5e3ee6d103d395bdc2134733"), "ListOfTechnology" : [ "Spring", "Hibernate" ] }
{ "_id" : ObjectId("5e3ee6ec03d395bdc2134734"), "ListOfTechnology" : [ "Groovy" ] }
raja
Published on 30-Mar-2020 12:54:40
Advertisements