Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

1 Answer
Samual Sam

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"
   ]
}

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.