MongoDB query to remove item from array?


To remove item from array, you can use $pull operator. Let us create a collection with documents −

> db.removeItemFromArray.insertOne(
   { "_id":101, "StudentName":"Larry", "StudentSubjects":["C","MongoDB","Java","MySQL"] } );
{ "acknowledged" : true, "insertedId" : 101 }

Display all documents from a collection with the help of find() method. The query is as follows −

> db.removeItemFromArray.find().pretty();

This will produce the following output −

{
   "_id" : 101,
   "StudentName" : "Larry",
   "StudentSubjects" : [
      "C",
      "MongoDB",
      "Java",
      "MySQL"
   ]
}

Following is the query to remove item from an array −

> db.removeItemFromArray.update(
...    { },
...    { $pull: {StudentSubjects:"Java" } },
...    { multi: true }
... );
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

In the above query, we have removed “Java”. Let us now display the documents from the collection −

> db.removeItemFromArray.find().pretty();

This will produce the following output −

{
   "_id" : 101,
   "StudentName" : "Larry",
   "StudentSubjects" : [
      "C",
      "MongoDB",
      "MySQL"
   ]
}

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

184 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements