如何使用前缀字符串更新数组中的所有元素?

要使用前缀字符串更新数组中的所有元素,请使用forEach()。首先让我们创建一个包含文档的集合-

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

以下是在find()方法的帮助下显示集合中所有文档的查询-

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

这将产生以下输出-

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

以下是用前缀字符串替换数组中所有元素的查询。前缀字符串是“ 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}}
   );
});

让我们再次检查文档-

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

这将产生以下输出-

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