如何替换 mongodb 中的字符串(带有示例)


您可以使用以下语法来替换 MongoDB 中字段中的特定字符串:

 db.myCollection.updateMany(
  { fieldName: { $regex : /old/ } },
  [{
    $set : { fieldName: {
      $replaceOne : { input: " $fieldName ", find: " old ", replacement: " new " }
    }}
  }]
)

此特定示例将名为myCollection 的集合中名为“fieldName”的字段中的字符串“old”替换为“new”。

以下示例展示了如何在具有以下文档的催收团队的实践中使用此语法:

 db.teams.insertOne({team: " Mavs ", conference: " Western ", points: 31})
db.teams.insertOne({team: " Spurs ", conference: " Western ", points: 22})
db.teams.insertOne({team: " Rockets ", conference: " Western ", points: 19})
db.teams.insertOne({team: " Celtics ", conference: " Eastern ", points: 26})
db.teams.insertOne({team: " Cavs ", conference: " Eastern ", points: 33})
db.teams.insertOne({team: " Nets ", conference: " Eastern ", points: 38})

示例:替换 MongoDB 中的字符串

我们可以使用以下代码将会议字段中的字符串“Western”替换为“West”:

 db.teams.updateMany(
  { conference: { $regex : /Western/ } },
  [{
    $set : { conference: {
      $replaceOne : { input: " $conference ", find: " Western ", replacement: " West " }
    }}
  }]
)

更新后的集合现在如下所示:

 { _id: ObjectId("620139494cb04b772fd7a8fa"),
  team: ' Mavs ',
  conference: ' West ',
  points: 31 }
{ _id: ObjectId("620139494cb04b772fd7a8fb"),
  team: ' Spurs ',
  conference: ' West ',
  points: 22 }
{ _id: ObjectId("620139494cb04b772fd7a8fc"),
  team: ' Rockets ',
  conference: ' West ',
  points: 19 }
{ _id: ObjectId("620139494cb04b772fd7a8fd"),
  team: ' Celtics ',
  conference: ' Eastern ',
  points: 26 }
{ _id: ObjectId("620139494cb04b772fd7a8fe"),
  team: ' Cavs ',
  conference: ' Eastern ',
  points: 33 }
{ _id: ObjectId("620139494cb04b772fd7a8ff"),
  team: ' Nets ',
  conference: ' Eastern ',
  points: 38 }

请注意,会议字段中包含字符串“Western”的每个文档现在会议字段中都包含“Western”。

会议字段中没有字符串“Western”的任何文档都只保留其原始字符串。

注意:您可以在此处找到$replaceOne函数的完整文档。

其他资源

以下教程解释了如何在 MongoDB 中执行其他常见操作:

MongoDB:如何检查字段是否包含字符串
MongoDB:如何添加新字段
MongoDB:如何删除字段

添加评论

您的电子邮箱地址不会被公开。 必填项已用*标注