$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.
| Category | String |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $regexReplace: { input: <string-expression>, regex: <pattern>, replacement: <replacement>, options: <options> } }
⚙️ Parameters
| input | Required; the string to process. |
|---|---|
| regex | Required; a Perl-compatible regex pattern string. |
| replacement | Required; the replacement, with $1/$2 referencing capture groups. |
| options | Optional 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
- $1/$2 in replacement reference capture groups; escape a literal $
- Unlike $replaceAll (literal), $regexReplace replaces by pattern
- No match means the input is returned unchanged
🏷️ Related Tags
💡 Related Cases
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.