$replaceOne (Replace First Match)

Last updated: 2026-10-09

$replaceOne (Replace First Match)

$replaceOne replaces the first occurrence of a substring in a string with a given replacement — handy for typo fixes or prefix swaps. find must be a non-empty string or it throws; when find does not occur, the input is returned unchanged. It is literal replacement with no regex support — use $regexReplace for patterns. Null or missing input yields null.

CategoryString
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

{ $replaceOne: { input: <string-expression>, find: <find>, replacement: <replacement> } }

⚙️ Parameters

inputRequired; the string to process.
findRequired; a non-empty search string.
replacementRequired; the replacement string.

Returns:The replaced string; null if input is null.

▶ Example

Run the commands below in your local mongosh (requires a running mongod):

// $replaceOne: fix a typo in post bodies
 db.posts.aggregate([
  { $project: { fixed: { $replaceOne: { input: '$body', find: 'teh', replacement: 'the' } } } }
])

Output:

{ "_id": 1, "fixed": "the quick brown fox" }
{ "_id": 2, "fixed": "no typo here" }

📌 Notes

More hands-on cases coming soon.

📚 Related Tutorials

❓ FAQ

QCan it replace all matches?
ANo — use $replaceAll for all occurrences.
QCan find be an empty string?
ANo — it throws.
QDoes it support regex?
ANo — use $regexReplace for pattern replacement.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏