在MongoDB中替换子字符串的2种方法

发布于

MongoDB 4.4引入了九个新的聚合管道运算符,其中包括两个用于查找和替换子字符串的新运算符。

允许您查找和替换子字符串的两个新运算符是 and 运算符。$replaceOne``$replaceAll

以下是每个运算符的作用:

算子 描述
[$replaceOne](https://database.guide/mongodb-replaceone/ "MongoDB $replaceOne") 将输入字符串中搜索字符串的第一个实例替换为替换字符串。
[$replaceAll](https://database.guide/mongodb-replaceall/ "MongoDB $replaceAll") 将输入字符串中搜索字符串的所有实例替换为替换字符串。

这些运算符之间的唯一区别是替换子字符串的第一个实例,而替换子字符串_的所有__实例。_$replaceOne``$replaceAll

运营商$replaceOne

假设我们有一个调用的集合,其中包含以下文档:products

{ “_id” : 1, “product” : “Left Handed Screwdriver with Left Handed Carry Case” }

我们可以使用运算符将子字符串的第一个实例替换为另一个字符串:$replaceOne``Left Handed

db.products.aggregate([
   {
     $project:
      {
         product: { $replaceOne: { input: "$product", find: "Left Handed", replacement: "Ambidextrous" } }
      }
   }
]).pretty()

输出:

{
	"_id" : 1,
	"product" : "Ambidextrous Screwdriver with Left Handed Carry Case"
}

请注意,子字符串 () 实际上有两个实例,但只替换了第一个实例。Left Handed

运营商$replaceAll

在前面的示例中,我们替换了子字符串的第一个实例。

现在让我们使用运算符替换子字符串_的所有_实例:$replaceAll

db.products.aggregate([
   {
     $project:
      {
         product: { $replaceAll: { input: "$product", find: "Left Handed", replacement: "Ambidextrous" } }
      }
   }
]).pretty()

输出:

{
	"_id" : 1,
	"product" : "Ambidextrous Screwdriver with Ambidextrous Carry Case"
}

这次替换了子字符串 () 的两个实例。Left Handed