MongoDB $regexMatch Operator

Beginner
5 min read
Updated: Oct 2026
3 examples
Live preview

What Is $regexMatch?

$regexMatch is a MongoDB aggregation expression that tests whether a regular expression matches a string and returns true or false. It does not return the matched text—only a yes/no answer.

Remember
$regexMatch ≈ /pattern/.test(string)

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

match exists → true
no match     → false
case-sensitive by default (use options: "i")
UsePrefer
True / false only$regexMatch
First match details$regexFind
Every match details$regexFindAll

How to Use $regexMatch in MongoDB

Pass the input string, the pattern, and optional regex options.

  1. Choose an expression stage ($addFields, $project, or $cond).
  2. Set input to a string field (for example "$text").
  3. Set regex to a pattern string or /pattern/.
  4. Optional: add options such as "i", or filter with $expr inside $match.
PieceRequired?Role
inputYesString to test
regexYesPattern as string or /.../
optionsNoi, m, x, s (not both here and on the regex)

Pseudocode

Pseudocode
for each document:
    s = evaluate(input)
    pattern = evaluate(regex)
    if pattern matches anywhere in s:
        result = true
    else:
        result = false
    emit { ..., field: result }

Cheat Sheet

Keep these facts handy while writing boolean regex tests.

TopicDetail
TypeAggregation expression (boolean)
Syntax{ $regexMatch: { input, regex, options? } }
Resulttrue or false
DefaultCase-sensitive; collation ignored
Case-insensitiveoptions: "i" or /pattern/i
Filter docs$match: { $expr: { $regexMatch: { ... } } }
Need match text?Use $regexFind / $regexFindAll

Live Preview

Text: "Email me at [email protected]". Pick a pattern and see true or false.

Simulates $regexMatch boolean results (same idea as the mongosh examples).

Result
input = "Email me at [email protected]"
regex = /@mongodb\.com/i
$regexMatch → true

{ matched: true }

Worked Walkthrough — Phone vs Email

Same idea as /pattern/.test(text) in JavaScript: does the pattern appear anywhere?

Calculation
text = "Call 555-0199 today"

/\d{3}-\d{4}/.test(text)  → true   (phone found)
/@mongodb\.com/i.test(text) → false  (no email)

text2 = "Email me at [email protected]"

/@mongodb\.com/.test(text2)  → false  (case-sensitive: MongoDB ≠ mongodb)
/@mongodb\.com/i.test(text2) → true   (i ignores case)

$regexMatch returns only the boolean — not the match text.

MongoDB Examples

We use a small notes collection with a text field. First we flag phone-like patterns, then we categorize notes by email with a case-insensitive check. Insert the sample data once in mongosh.

Example 1 — Sample Data

Imagine three short notes. Each has an id and a text string. We save them in a collection named notes.

mongosh
db.notes.insertMany([
  { _id: 1, text: "Call 555-0199 today" },
  { _id: 2, text: "No phones here" },
  { _id: 3, text: "Email me at [email protected]" }
]);

How the Data Is Stored in MongoDB

After the insert, MongoDB keeps three documents in notes. Run find() to see them:

mongosh
db.notes.find()

Read those documents like this:

Field in MongoDBExamplePlain English
_id1Note id for this lesson
text"Call 555-0199 today"String we will test with regex
Picture
Note 1: has "555-0199"  → phone pattern? true
Note 2: plain sentence  → phone pattern? false
Note 3: has email       → phone pattern? false

How It Works

  1. Insert once. insertMany adds three note documents.
  2. MongoDB stores strings as written. Digits, @, and case are kept exactly.
  3. find() shows the same shape. What you inserted is what you get back—ready for $regexMatch next.

Example 2 — Boolean Flag

Goal: add has_phone — true when the note contains a ###-#### style number.

mongosh
db.notes.aggregate([
  {
    $addFields: {
      has_phone: {
        $regexMatch: {
          input: "$text",
          regex: /\d{3}-\d{4}/
        }
      }
    }
  }
]);

How It Works

  1. Read the stored string. input: "$text" is the note body.
  2. Apply the pattern. \d{3}-\d{4} means three digits, a hyphen, four digits.
  3. Boolean only. Note 1 → true; the others → false.
  4. No match text. Unlike $regexFind, you do not get "555-0199" back—just the flag.

Example 3 — $cond With Case-Insensitive Option

Goal: label notes that mention an @mongodb.com address as "staff", otherwise "other". Use option i so MongoDB still matches.

mongosh
db.notes.aggregate([
  {
    $addFields: {
      kind: {
        $cond: [
          {
            $regexMatch: {
              input: "$text",
              regex: /@mongodb\.com/,
              options: "i"
            }
          },
          "staff",
          "other"
        ]
      }
    }
  }
]);

How It Works

  1. Same stored documents. Still using the three notes from Example 1.
  2. Case-insensitive test. options: "i" lets @MongoDB.com match @mongodb.com.
  3. Branch with $cond. true → "staff"; false → "other".
  4. Only note 3 is staff. The phone notes have no matching email domain.

Edge Cases & Pitfalls

Check these before using $regexMatch in production pipelines.

boolean

Only true / false

If you need the matched text or indexes, switch to $regexFind or $regexFindAll.

options

Do not double-specify options

Put flags either on the regex literal (/pat/i) or in options—not both. Use options for s / x.

case

Collation is ignored

Default matching is case-sensitive. Use i when you want case-insensitive checks.

query

Filtering documents

In aggregation, wrap with $match + $expr. For simple find filters, $regex is often enough.

Performance Notes

ApproachCostBest for
$regexMatchCan stop at first hitFlags, validation, branching
$regexFind / $regexFindAllMore work + larger outputWhen you need match details
Query $regexFilter at query timeSimple document filters in find()

Prefer $regexMatch when a boolean is enough—it is lighter than collecting match objects. Still keep patterns focused, and filter early with $match when only some rows need the test.

Key Takeaways

  • Role: regex existence test → true / false.
  • Not details: no match / idx / captures.
  • Case: default sensitive; use i when needed.
  • Pair with: $cond for labels; $expr for filters.

One line: $regexMatch answers “does this pattern appear?”—true or false, nothing more.

Frequently Asked Questions

$regexMatch tests whether a regular expression matches anywhere in a string and returns true or false. It does not return the matched text—only a boolean.
Use { $regexMatch: { input: <string>, regex: <pattern>, options: <options> } } inside stages like $project, $addFields, $cond, or $match with $expr. The options field is optional.
$regex is a query filter used in find() / $match to keep whole documents. $regexMatch is an aggregation expression that evaluates one string and returns true or false.
Use $regexMatch when you only need to know if a pattern exists. Use $regexFind or $regexFindAll when you need the matched text, position, or capture groups.
No. $regexMatch ignores collation and is case-sensitive by default. Use the i option for case-insensitive matching.
If there is no match—including when the input does not contain the pattern—the result is false. Prefer guarding missing fields when needed.

Next: $reverseArray

Reverse the order of elements in an array.

$reverseArray tutorial →

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.

9 people found this page helpful