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
   ]
}
raja
Published on 13-Jun-2019 15:21:17
Advertisements