$regexReplace (Regex Replace)

Last updated: 2026-10-09

$regexReplace (Regex Replace)

$regexReplace matches text with a regex and replaces it with a given string — an advanced text-cleaning tool in pipelines. The replacement can reference capture groups via $1, $2 for extract-and-rebuild flows. options supports flags like i, m, x. Unlike $replaceAll (literal only), $regexReplace works on patterns. Introduced in MongoDB 4.4. Null input yields null.

CategoryString
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

{ $regexReplace: { input: <string-expression>, regex: <pattern>, replacement: <replacement>, options: <options> } }

⚙️ Parameters

inputRequired; the string to process.
regexRequired; a Perl-compatible regex pattern string.
replacementRequired; the replacement, with $1/$2 referencing capture groups.
optionsOptional flags such as i, m, x.

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

▶ Example

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

// $regexReplace: mask the middle 4 digits of phone numbers
 db.users.aggregate([
  { $project: { masked: { $regexReplace: { input: '$phone', regex: '(\\d{3})\\d{4}(\\d{4})', replacement: '$1****$2' } } } }
])

Output:

{ "_id": 1, "masked": "138****8000" }
{ "_id": 2, "masked": "139****1234" }

📌 Notes

More hands-on cases coming soon.

📚 Related Tutorials

❓ FAQ

QHow to reference capture groups in the replacement?
AUse $1, $2 in capture-group order.
QWhat if nothing matches?
AThe input is returned unchanged.
QWhich to choose, $regexReplace or $replaceAll?
APatterns need $regexReplace; plain literal swaps are faster with $replaceAll.
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%

🙏 帮我们做得更好

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

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