$replaceAll(替换全部匹配)
最后更新:2026-10-09
$replaceAll(替换全部匹配)
$replaceAll 把字符串中所有出现的子串都替换为指定字符串,适合批量清洗脏数据、统一分隔符等场景。find 必须非空,否则报错;未找到时返回原字符串。它是字面量替换,与 $replaceOne 的区别是替换全部而不是第一个。需要模式匹配时用 $regexReplace。input 为 null 或缺失时返回 null。
| 分类 | 字符串 |
|---|---|
| MongoDB 版本 | 1.0+ |
| 示例语言 | mongosh (Shell) |
📝 语法
{ $replaceAll: { input: <字符串表达式>, find: <查找串>, replacement: <替换串> } }
⚙️ 参数
| input | 必填,要处理的字符串。 |
|---|---|
| find | 必填,非空查找串。 |
| replacement | 必填,替换串。 |
返回值:替换后的字符串;input 为 null 时返回 null。
▶ 示例
请在本地安装的 mongosh 中执行以下命令(需已启动 mongod):
// $replaceAll:去掉手机号中的所有连字符
db.users.aggregate([
{ $project: { clean: { $replaceAll: { input: '$phone', find: '-', replacement: '' } } } }
])
运行结果:
{ "_id": 1, "clean": "13800138000" }
{ "_id": 2, "clean": "13900139000" }
📌 注意事项
- 替换所有出现,与 $replaceOne 对应
- find 为空字符串会报错
- 性能上优于循环多次 $replaceOne
🏷️ 相关标签
💡 相关案例
更多实战案例即将上线,敬请期待。
📚 相关教程
❓ 常见问题
Q和 $replaceOne 区别?
A$replaceOne 只换第一个,$replaceAll 全部换。
Q能配合正则吗?
A不能,正则用 $regexReplace。
Q替换为空串可以吗?
A可以,效果是删除所有匹配的 find。