$replaceOne(替换第一个匹配)
最后更新:2026-10-09
$replaceOne(替换第一个匹配)
$replaceOne 把字符串中第一次出现的子串替换为指定字符串,常用于修正拼写错误、替换前缀等。find 必须是非空字符串,否则报错;未找到 find 时返回原字符串不变。它是字面量替换,不支持正则,需要模式匹配时用 $regexReplace。input 为 null 或缺失时返回 null。
| 分类 | 字符串 |
|---|---|
| MongoDB 版本 | 1.0+ |
| 示例语言 | mongosh (Shell) |
📝 语法
{ $replaceOne: { input: <字符串表达式>, find: <查找串>, replacement: <替换串> } }
⚙️ 参数
| input | 必填,要处理的字符串。 |
|---|---|
| find | 必填,非空查找串。 |
| replacement | 必填,替换串。 |
返回值:替换后的字符串;input 为 null 时返回 null。
▶ 示例
请在本地安装的 mongosh 中执行以下命令(需已启动 mongod):
// $replaceOne:修正正文中的拼写错误
db.posts.aggregate([
{ $project: { fixed: { $replaceOne: { input: '$body', find: 'teh', replacement: 'the' } } } }
])
运行结果:
{ "_id": 1, "fixed": "the quick brown fox" }
{ "_id": 2, "fixed": "no typo here" }
📌 注意事项
- 只替换第一次出现的位置
- find 为空字符串会报错
- 未找到时原样返回 input
🏷️ 相关标签
💡 相关案例
更多实战案例即将上线,敬请期待。
📚 相关教程
❓ 常见问题
Q能替换所有匹配吗?
A不能,全部替换用 $replaceAll。
Qfind 能是空字符串吗?
A不能,会报错。
Q支持正则吗?
A不支持,模式替换用 $regexReplace。