$regexMatch (Regex Test)
Last updated: 2026-10-09
$regexMatch (Regex Test)
$regexMatch tests whether a string matches a regex and returns true or false — the lightest regex operator, ideal for filtering and data validation. It only answers "does it match?" and returns no content; use $regexFind to extract matches. options accepts flags like i, m, s, and x. Null or missing input yields null.
| Category | String |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $regexMatch: { input: <string-expression>, regex: <pattern>, options: <options> } }
⚙️ Parameters
| input | Required; the string to test. |
|---|---|
| regex | Required; a Perl-compatible regex pattern string. |
| options | Optional flags such as i, m, s, x. |
Returns:true if it matches, false otherwise; null if input is null.
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $regexMatch: is the email a Gmail address (case-insensitive)
db.users.aggregate([
{ $project: { isGmail: { $regexMatch: { input: '$email', regex: '@gmail\\.com$', options: 'i' } } } }
])
Output:
{ "_id": 1, "isGmail": true }
{ "_id": 2, "isGmail": false }
📌 Notes
- Returns a boolean — usable directly in $expr of $match
- regex is a pattern string; anchors like ^ and $ work
- Tests only; use $regexFind when you need the matched content
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QCan it be used inside $match?
AYes — wrap it in $expr.
QDoes it only return a boolean?
AYes — true or false, with no match content.
QHow to ignore case?
APass 'i' in options.