How can I update all elements in an array with a prefix string?


To update all elements in an array with a prefix string, use forEach(). Let us first create a collection with documents −

> db.replaceAllElementsWithPrefixDemo.insertOne(
   {
      "StudentNames" : [
         "John",
         "Carol"
      ]
   }
);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd91908b50a6c6dd317ad8e")
}
>
>
> db.replaceAllElementsWithPrefixDemo.insertOne(
   {
      "StudentNames" : [
         "Sam"
      ]
   }
);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd9191cb50a6c6dd317ad8f")
}

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

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

This will produce the following output −

{
   "_id" : ObjectId("5cd91908b50a6c6dd317ad8e"),
   "StudentNames" : [
      "John",
      "Carol"
   ]
}
{
   "_id" : ObjectId("5cd9191cb50a6c6dd317ad8f"),
   "StudentNames" : [
         "Sam"
   ]
}

Following is the query to replace all elements in an array with a prefix string. The prefix string is “MR” −

> db.replaceAllElementsWithPrefixDemo.find().forEach(function (myDocumentValue) {
   var prefixValue = myDocumentValue.StudentNames.map(function (myValue) {
      return "MR." + myValue;
   });
   db.replaceAllElementsWithPrefixDemo.update(
      {_id: myDocumentValue._id},
      {$set: {StudentNames: prefixValue}}
   );
});

Let us check the document once again −

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

This will produce the following output −

{
   "_id" : ObjectId("5cd91908b50a6c6dd317ad8e"),
   "StudentNames" : [
      "MR.John",
      "MR.Carol"
   ]
}
{
   "_id" : ObjectId("5cd9191cb50a6c6dd317ad8f"),
   "StudentNames" : [
      "MR.Sam"
   ]
}
raja
Published on 13-Jun-2019 14:43:15
Advertisements