Make MongoDB replace single array value with string?


To replace, use $set and positional($) operator. Let us create a collection with documents −

> db.demo564.insertOne({"StudentName":["Chris","David","Mike","Sam"]});{
   "acknowledged" : true, "insertedId" : ObjectId("5e90880a39cfeaaf0b97b576")
}

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

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

This will produce the following output −

{
   "_id" : ObjectId("5e90880a39cfeaaf0b97b576"),
   "StudentName" : [
      "Chris",
      "David",
      "Mike",
      "Sam"
   ]
}

Following is the query to replace single array value with string −

> db.demo564.updateMany(
...    { "StudentName": "David" },
...    { "$set": { "StudentName.$": "Carol Taylor" } }
... )
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
>

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

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

This will produce the following output −

{
   "_id" : ObjectId("5e90880a39cfeaaf0b97b576"),
   "StudentName" : [
      "Chris",
      "Carol Taylor",
      "Mike",
      "Sam"
   ]
}

Updated on: 14-May-2020

502 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements