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

CategoryString
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

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

⚙️ Parameters

inputRequired; the string to search.
regexRequired; a Perl-compatible regex pattern string.
optionsOptional 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

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

🙏 帮我们做得更好

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

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