MongoDB $regexMatch Operator

Beginner
⏱️ 8 min read
📚 Updated: Jul 2026
🎯 4 Examples
Pattern Match

What You’ll Learn

The $regexMatch operator checks whether a regular expression pattern appears in a string and returns true or false. Use it for validation, filtering, and conditional logic — without extracting match text.

01

Boolean Test

true or false.

02

Same Syntax

input + regex.

03

$match Stage

Filter in pipelines.

04

$cond Logic

Branch on pattern.

05

Validation

Email, SKU, format.

06

vs $regexFind

Check vs extract.

Definition and Usage

In MongoDB’s aggregation framework, the $regexMatch operator tests whether a regular expression pattern matches anywhere in a string. The result is a boolean: true if at least one match exists, false otherwise.

Unlike $regexFind and $regexFindAll, $regexMatch does not return matched text, positions, or capture groups. It answers a simple question: “Does this pattern appear in the string?”

💡
Beginner Tip

Use $regexMatch inside the aggregation $match stage to filter documents by a string pattern. Use $project to add a validation flag like isValidEmail: true.

📝 Syntax

The $regexMatch operator shares the same argument shape as $regexFind:

mongosh
{
  $regexMatch: {
    input: <string expression>,
    regex: <pattern expression>,
    options: <options expression>  // optional
  }
}

Return Value

mongosh
true   // pattern found in input
false  // no match, or input is null

Syntax Rules

  • input — the string to test (field path or expression).
  • regex — the pattern string or BSON regex literal.
  • options — optional flags like "i" (case insensitive).
  • Returns true when the pattern matches at least once.
  • Returns false when there is no match or when input is null.
  • Use in $match, $project, $addFields, $set, or $cond (MongoDB 4.2+).

💡 $regexMatch vs $regex vs $regexFind vs $regexFindAll

$regex — query filter; includes/excludes whole documents
$regexMatch — aggregation expression; true/false for one string
$regexFind — aggregation expression; first match object or null
$regexFindAll — aggregation expression; array of all match objects

⚡ Quick Reference

QuestionAnswer
Operator typeAggregation expression operator (string / regex)
Syntax{ $regexMatch: { input, regex, options? } }
Outputtrue or false
Extracts text?No — boolean only
Common stages$match, $project, $cond
Basic test
{
  $regexMatch: {
    input: "$email",
    regex: "@"
  }
}

Contains @

Case insensitive
{
  options: "i"
}

Ignore case

$match filter
$match: {
  $expr: { $regexMatch: ... }
}

Filter docs

No match
false

Pattern absent

Examples Gallery

Validate email format, filter posts with hashtags, branch with $cond, and run case-insensitive checks using $regexMatch.

📚 Validation Flags

Add a boolean hasEmailFormat field with $regexMatch.

Sample Input Documents

Suppose you have a users collection:

mongosh
[
  {
    "_id": 1,
    "name": "Alice",
    "contact": "alice@example.com"
  },
  {
    "_id": 2,
    "name": "Bob",
    "contact": "bob-phone-only"
  },
  {
    "_id": 3,
    "name": "Carol",
    "bio": "MongoDB fan #database #nosql"
  }
]

Example 1 — Check Email-Like Format

Test whether contact looks like an email address:

mongosh
db.users.aggregate([
  {
    $project: {
      name: 1,
      contact: 1,
      hasEmailFormat: {
        $regexMatch: {
          input: "$contact",
          regex: "^[\\w.-]+@[\\w.-]+\\.[a-zA-Z]{2,}$"
        }
      }
    }
  }
])

How It Works

The pattern checks for user@domain.tld structure. $regexMatch returns true or false only — no matched substring is returned.

📈 Filtering and Branching

Filter documents in $match and branch with $cond.

Example 2 — Filter Posts With Hashtags

Keep only documents whose bio contains a hashtag:

mongosh
db.users.aggregate([
  {
    $match: {
      $expr: {
        $regexMatch: {
          input: "$bio",
          regex: "#\\w+"
        }
      }
    }
  },
  {
    $project: { name: 1, bio: 1 }
  }
])

// Returns Carol only

How It Works

Wrap $regexMatch in $expr inside $match so MongoDB evaluates it as an aggregation expression, not a query operator.

Example 3 — Categorize With $cond

Assign a label based on whether the contact field is email-like:

mongosh
db.users.aggregate([
  {
    $project: {
      name: 1,
      contact: 1,
      contactType: {
        $cond: [
          {
            $regexMatch: {
              input: "$contact",
              regex: "@"
            }
          },
          "email",
          "other"
        ]
      }
    }
  }
])

// Alice: "email", Bob: "other"

How It Works

$cond uses the boolean from $regexMatch as its condition. This is cleaner than comparing $regexFind results to null when you only need yes/no.

Example 4 — Case-Insensitive Pattern Check

Test whether a SKU starts with PRO regardless of case:

mongosh
db.products.aggregate([
  {
    $project: {
      sku: 1,
      isProLine: {
        $regexMatch: {
          input: "$sku",
          regex: "^PRO-",
          options: "i"
        }
      }
    }
  }
])

// "pro-1001" → true
// "DEV-2002" → false

How It Works

The i option makes the pattern case insensitive. ^PRO- anchors the match to the start of the string.

Bonus — Validate Phone Number Pattern

Flag contacts that look like US phone numbers:

mongosh
db.users.aggregate([
  {
    $project: {
      name: 1,
      contact: 1,
      looksLikePhone: {
        $regexMatch: {
          input: "$contact",
          regex: "^\\d{3}-\\d{3}-\\d{4}$"
        }
      }
    }
  }
])

// "555-123-4567" → true
// "alice@example.com" → false

How It Works

\d{3}-\d{3}-\d{4} matches a simple ###-###-#### format. Use $regexMatch for quick format checks; use $regexFind if you need to extract the digits.

🚀 Use Cases

  • Format validation — flag emails, phone numbers, SKUs, or IDs that match a pattern.
  • Pipeline filtering — use $match + $expr to keep documents whose fields match a regex.
  • Conditional fields — branch with $cond based on pattern presence.
  • Data quality reports — add boolean columns for auditing without extracting match text.

🧠 How $regexMatch Works

1

MongoDB evaluates input and regex

The pipeline resolves the string (input) and compiles the pattern (regex) with any options.

Input
2

The engine searches for a match

MongoDB scans the string for at least one substring that satisfies the pattern. It stops as soon as a match is found.

Search
3

A boolean is returned

true if a match exists; false if not. No match text or position is included.

Result
=

true or false

Use in $match, $cond, or store as a validation flag.

Conclusion

The $regexMatch operator tests whether a regular expression pattern appears in a string and returns true or false. It is the right choice when you need validation or filtering without extracting match details.

Pair it with $match and $expr to filter documents, or with $cond for branching. For matched text, use $regexFind or $regexFindAll. Next in the series: $reverseArray.

💡 Best Practices

✅ Do

  • Use $regexMatch when you only need true/false
  • Wrap in $expr when using inside aggregation $match
  • Use options: "i" for case-insensitive checks
  • Prefer $regexFind when you need the matched substring
  • Keep patterns readable and test them in mongosh first

❌ Don’t

  • Expect match text or idx from $regexMatch
  • Use $regexMatch without $expr in aggregation $match
  • Compare $regexFind to null when a boolean suffices
  • Rely on regex alone for strict email/phone validation in production
  • Confuse $regexMatch with query $regex

Key Takeaways

Knowledge Unlocked

Five things to remember about $regexMatch

Use these points when testing patterns in aggregation pipelines.

5
Core concepts
📝 02

input + regex

Same shape as $regexFind.

Syntax
🛠 03

No extraction

Check only.

Output
🗃 04

$expr + $match

Filter documents.

Filtering
05

false

null input or no match.

Edge case

❓ Frequently Asked Questions

$regexMatch tests whether a regular expression pattern matches anywhere in a string and returns true or false. It does not return the matched text — only a boolean result.
The syntax is { $regexMatch: { input: <string>, regex: <pattern>, options: <options> } }. Use inside $match, $project, $addFields, $set, or $cond. The options field is optional.
A boolean: true when the pattern matches at least once in the input string, false when it does not. If input is null, the result is false.
$regex is a query filter operator used in find() and $match to include or exclude whole documents. $regexMatch is an aggregation expression that evaluates a single string field and returns true or false.
Use $regexMatch when you only need to know if a pattern exists (validation, filtering, flags). Use $regexFind or $regexFindAll when you need the matched text, position, or capture groups.

Continue the Operator Series

Move on to $reverseArray for array manipulation, or review $regexFindAll to extract every match.

Next: $reverseArray →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

5 people found this page helpful