$regexFind (First Regex Match)
Last updated: 2026-10-09
$regexFind (First Regex Match)
$regexFind runs a Perl-compatible regex search on a string and returns the first match as a document (with match, idx, and captures fields), or null when nothing matches. regex takes the pattern string directly; options accepts flags like i (case-insensitive) and m (multiline). Unlike $regexMatch it also returns capture groups, so it fits extraction and subgroup tasks.
| Category | String |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $regexFind: { input: <string-expression>, regex: <pattern>, options: <options> } }
⚙️ Parameters
| input | Required; the string to search. |
|---|---|
| regex | Required; a Perl-compatible regex pattern string. |
| options | Optional flags such as i, m, x. |
Returns:A match document { match, idx, captures }; null when no match or input is null.
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $regexFind: extract an 11-digit phone from contacts
db.users.aggregate([
{ $project: { phone: { $regexFind: { input: '$contact', regex: '[0-9]{11}', options: 'i' } } } }
])
Output:
{ "_id": 1, "phone": { "match": "13800138000", "idx": 5, "captures": [] } }
{ "_id": 2, "phone": null }
📌 Notes
- No match returns null, not an empty document
- captures holds the capture groups; empty when there are none
- options supports i (ignore case), m (multiline), x (ignore whitespace)
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QDoes null mean no match?
AYes — no match yields null; guard with $ifNull.
QHow to get capture groups?
AThe captures field lists group contents in order.
QCan options combine flags?
AYes — e.g. 'im' enables both ignore-case and multiline.