在 MongoDB 中替换子字符串的 2 种方法($replaceOne 与 $replaceAll)

详细介绍 MongoDB 聚合管道中用于查找和替换子字符串的两个常用字符串操作符:$replaceOne(仅替换首个匹配项)与 $replaceAll(替换所有匹配项),并附带实战代码示例。

发布于

在 MongoDB 聚合管道处理文本数据时,经常需要对字符串中的特定子串进行替换。MongoDB 提供了两个专用的字符串聚合操作符:

  • $replaceOne:仅替换输入字符串中第一个匹配的子字符串。
  • $replaceAll:替换输入字符串中所有匹配的子字符串。

两者的参数结构完全一致,核心差异在于替换的范围:

操作符 功能描述
$replaceOne 将输入字符串中首次出现的搜索子串替换为目标字符串
$replaceAll 将输入字符串中所有出现的搜索子串全部替换为目标字符串

两者的语法格式如下:

{ $replaceOne: { input: <表达式>, find: <搜索子串>, replacement: <替换目标> } }
{ $replaceAll: { input: <表达式>, find: <搜索子串>, replacement: <替换目标> } }

准备示例文档

假设我们有一个名为 products 的集合,包含如下记录:

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

注意该文档中的 product 字段包含两处 "Left Handed" 子串。

方法 1:使用 $replaceOne 操作符

如果我们只想替换文本中第一次出现的 "Left Handed",可以使用 $replaceOne 操作符:

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

输出:

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

如结果所示,前部的 "Left Handed Screwdriver" 被替换为了 "Ambidextrous Screwdriver",而后面的 "Left Handed Carry Case" 保持不变。

方法 2:使用 $replaceAll 操作符

若需要将字符串中所有出现的 "Left Handed" 全部替换为 "Ambidextrous",则应使用 $replaceAll 操作符:

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

输出:

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

两处 "Left Handed" 均已被替换为 "Ambidextrous"。

注意事项

[!NOTE]

  1. 区分大小写:find 参数匹配是严格区分大小写的。例如 "left handed" 无法匹配 "Left Handed"。
  2. Null 与缺失字段:若 input、find 或 replacement 中任意一个参数解析为 null 或字段不存在,$replaceOne 和 $replaceAll 将直接返回 null。
  3. 更新持久化:上述聚合仅用于查询投影。若需将替换结果持久化写回集合,可配合 $set 与 db.collection.updateMany([], [ { $set: ... } ]) 运行聚合更新管道。