How do I remove a string from an array in a MongoDB document?


You can use $pull operator to remove a string from an array. Let us first create a collection with documents −

> db.removeAStringDemo.insertOne({"Score":[45,67,89,"John",98,99,67]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cda5224b50a6c6dd317adbd")
}

Following is the query to display all documents from a collection with the help of find() method −

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

This will produce the following output −

{
   "_id" : ObjectId("5cda5224b50a6c6dd317adbd"),
   "Score" : [
      45,
      67,
      89,
      "John",
      98,
      99,
      67
   ]
}

Following is the query to remove a string from an array in a MongoDB document. The string which is to be removed is “John” −

> db.removeAStringDemo.update( { _id :ObjectId("5cda5224b50a6c6dd317adbd") }, { $pull: { "Score":"John" }});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Let us check the document once again −

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

This will produce the following output −

{
   "_id" : ObjectId("5cda5224b50a6c6dd317adbd"),
   "Score" : [
      45,
      67,
      89,
      98,
      99,
      67
   ]
}

Updated on: 30-Jul-2019

301 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements