$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.
| Category | String |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $replaceOne: { input: <string-expression>, find: <find>, replacement: <replacement> } }
⚙️ Parameters
| input | Required; the string to process. |
|---|---|
| find | Required; a non-empty search string. |
| replacement | Required; 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
- Replaces only the first occurrence
- An empty find throws
- When find is absent, input is returned unchanged
🏷️ Related Tags
💡 Related Cases
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.