$replaceAll (Replace All Matches)
Last updated: 2026-10-09
$replaceAll (Replace All Matches)
$replaceAll replaces every occurrence of a substring with a given string — ideal for batch data cleaning or delimiter unification. find must be non-empty or it throws; when absent, the input is returned unchanged. It is literal replacement, differing from $replaceOne in replacing all instead of the first. Use $regexReplace for pattern matching. Null or missing input yields null.
| Category | String |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $replaceAll: { 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):
// $replaceAll: remove all hyphens from phone numbers
db.users.aggregate([
{ $project: { clean: { $replaceAll: { input: '$phone', find: '-', replacement: '' } } } }
])
Output:
{ "_id": 1, "clean": "13800138000" }
{ "_id": 2, "clean": "13900139000" }
📌 Notes
- Replaces every occurrence — the counterpart of $replaceOne
- An empty find throws
- More efficient than looping $replaceOne
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QWhat differs from $replaceOne?
A$replaceOne swaps the first; $replaceAll swaps every occurrence.
QCan it work with regex?
ANo — use $regexReplace for regex.
QCan the replacement be empty?
AYes — it deletes every occurrence of find.