$regexFindAll (All Regex Matches)
Last updated: 2026-10-09
$regexFindAll (All Regex Matches)
$regexFindAll runs a regex search on a string and returns every match as an array; each element has match, idx, and captures fields, and no match yields an empty array. It is ideal for extracting repeated patterns such as emails, links, or numbers. Unlike $regexFind, it never returns null — always an array, so $size counts matches directly.
| Category | String |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $regexFindAll: { 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. |
Returns:An array of match documents; empty when nothing matches; null if input is null.
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $regexFindAll: extract all links from posts
db.posts.aggregate([
{ $project: { links: { $regexFindAll: { input: '$body', regex: 'https?://[a-z0-9.]+' } } } }
])
Output:
{ "_id": 1, "links": [ { "match": "https://a.com", "idx": 10, "captures": [] }, { "match": "https://b.org", "idx": 32, "captures": [] } ] }
📌 Notes
- No match gives an empty array, not null — $size works directly
- Matching is global; it does not stop at the first hit
- Watch performance on large text; prescreen with $regexMatch if needed
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QWhat is returned when nothing matches?
AAn empty array, not null.
QHow to count the matches?
AWrap the result with $size.
QWhat differs from $regexFind?
A$regexFind returns the first match (null if none); $regexFindAll returns all matches.