$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.

CategoryString
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

{ $replaceAll: { 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):

// $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

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.
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%

🙏 帮我们做得更好

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

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