MongoDB $regex Operator

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

What You’ll Learn

The $regex operator filters documents where a string field matches a regular expression pattern. Use it for partial text search, prefix filters, email domain checks, and flexible pattern matching in find() and $match.

01

Pattern Match

Regex on strings.

02

$regex + $options

Pattern and flags.

03

Case Insensitive

Option i.

04

^ and $

Start / end anchors.

05

Use Cases

Search, filter, validate.

06

vs $text

Regex vs full-text.

Definition and Usage

In MongoDB, the $regex operator performs pattern matching on string fields. A document matches when the field value satisfies the regular expression. For example, { name: { $regex: "john", $options: "i" } } finds names containing “john” in any case.

$regex is a query operator used in find() filters and $match stages. It does not transform field values — it only includes or excludes documents based on whether the pattern matches.

💡
Beginner Tip

In mongosh you can write a shorthand: { name: /^john/i }. In application drivers, prefer the explicit { $regex: "pattern", $options: "i" } form for clarity and portability.

📝 Syntax

The $regex operator is applied to a field with a pattern and optional flags:

mongosh
{ field: { $regex: <pattern>, $options: <options> } }

Shorthand (mongosh)

mongosh
{ field: /pattern/options }

// Example:
{ name: /^admin/i }

Common $options Flags

  • i — case insensitive matching.
  • m — multiline mode (^ and $ match line boundaries).
  • x — extended mode (ignore whitespace in the pattern).
  • s — dot (.) matches newline characters.
  • Combine flags: $options: "im".

Syntax Rules

  • $regex applies to string fields (or values coerced to strings in some contexts).
  • Use ^ to anchor at the start and $ to anchor at the end.
  • Escape special regex characters in literals: \. for a dot, \\ for backslash.
  • Pair with $not to exclude pattern matches: { field: { $not: { $regex: ... } } }.
  • For full-text search at scale, consider the $text operator and text indexes.

💡 $regex vs $text vs $regexFind

$regex — query filter; returns documents that match a pattern
$text — full-text search with a text index; better for large search workloads
$regexFind — aggregation expression; extracts the matched substring from a field
Index tip^prefix (case-sensitive) can use indexes; .*suffix often cannot

⚡ Quick Reference

QuestionAnswer
Operator typeQuery operator (pattern matching)
Syntax{ field: { $regex: pattern, $options: flags } }
Common usagefind(), $match
Case insensitive$options: "i"
Exclude pattern{ $not: { $regex: ... } }
Contains
{
  name: {
    $regex: "john",
    $options: "i"
  }
}

Substring search

Starts with
{
  sku: {
    $regex: "^PRO-"
  }
}

Prefix anchor

Ends with
{
  email: {
    $regex: "@gmail\\.com$"
  }
}

Suffix anchor

Exclude
{
  email: {
    $not: {
      $regex: "^test"
    }
  }
}

Not test accounts

Examples Gallery

Search users by name, filter SKU prefixes, match email domains, exclude test accounts, and use $regex in aggregation pipelines.

📚 User Name Search

Find users whose name contains a substring with case-insensitive $regex.

Sample Input Documents

Suppose you have a users collection:

mongosh
[
  { "_id": 1, "name": "John Smith",   "email": "john@example.com" },
  { "_id": 2, "name": "Jane Johnson", "email": "jane@gmail.com" },
  { "_id": 3, "name": "Bob Wilson",   "email": "test.bob@example.com" },
  { "_id": 4, "name": "johnny Lee",   "email": "johnny@corp.com" }
]

Example 1 — Case-Insensitive Substring Search

Find names containing “john” in any case:

mongosh
db.users.find({
  name: {
    $regex: "john",
    $options: "i"
  }
})

How It Works

The i option makes the match case insensitive. “John”, “john”, and “JOHN” all match anywhere in the string.

📈 Practical Patterns

Prefix filters, domain matching, exclusions, and pipeline $match.

Example 2 — Starts With a Prefix

Find products whose SKU starts with PRO-:

mongosh
db.products.find({
  sku: { $regex: "^PRO-" }
})

// Matches: PRO-1001, PRO-ABCD
// Does not match: XPRO-1001

How It Works

The ^ anchor means “starts with.” Prefix patterns like this can use indexes when case-sensitive and anchored at the beginning.

Example 3 — Email Domain Match

Find users with Gmail addresses (escape the dot in .com):

mongosh
db.users.find({
  email: {
    $regex: "@gmail\\.com$",
    $options: "i"
  }
})

How It Works

$ anchors the match at the end. \. matches a literal dot. Together they target emails ending with @gmail.com.

Example 4 — Exclude Test Accounts with $not

Keep users whose email does not start with test:

mongosh
db.users.find({
  email: {
    $not: { $regex: "^test", $options: "i" }
  }
})

How It Works

$not negates the regex match. This excludes test.bob@example.com while keeping normal addresses.

Bonus — $regex in an Aggregation $match Stage

Filter a pipeline early for names matching a pattern:

mongosh
db.users.aggregate([
  {
    $match: {
      name: { $regex: "^J", $options: "i" }
    }
  },
  {
    $project: {
      name: 1,
      email: 1
    }
  }
])

// Names starting with J (case insensitive)

How It Works

$regex works the same in $match as in find(). Place the filter early to reduce documents processed by later stages.

Bonus — Search Multiple Fields with $or

Match if either name or email contains a term:

mongosh
db.users.find({
  $or: [
    { name:  { $regex: "john", $options: "i" } },
    { email: { $regex: "john", $options: "i" } }
  ]
})

How It Works

Combine $or with $regex when the search term might appear in different fields.

🚀 Use Cases

  • Search boxes — partial, case-insensitive name or title lookups.
  • SKU / code prefixes — filter product or order codes starting with a pattern.
  • Email validation — rough domain or format checks with anchored patterns.
  • Data cleanup — exclude test, demo, or internal accounts with $not + $regex.

🧠 How $regex Works

1

MongoDB evaluates the pattern

The regex engine compiles the pattern and options (i, m, etc.) for each query.

Input
2

Each document’s field is tested

MongoDB checks whether the field string matches the pattern. Non-string or missing fields typically do not match.

Match
3

Matching documents are returned

In find() or $match, only documents that pass the regex test continue in the result set.

Output
=

Flexible text filtering

Pattern-based queries without exact equality on full strings.

Conclusion

The $regex operator brings regular expression pattern matching to MongoDB queries. Use it for substring search, prefix and suffix filters, and exclusions with $not. Remember to escape special characters and choose patterns that work with your indexes when performance matters.

For extracting matched text inside pipelines, use $regexFind. Next in the series: $regexFind.

💡 Best Practices

✅ Do

  • Use ^prefix for index-friendly prefix searches (case-sensitive)
  • Escape dots and special regex characters in literal patterns
  • Use $options: "i" for case-insensitive search
  • Place $match with $regex early in pipelines
  • Consider $text for large-scale full-text search

❌ Don’t

  • Start patterns with .* on huge collections without indexes
  • Assume case-insensitive regex uses indexes efficiently
  • Forget to escape . when matching literal dots (e.g. domains)
  • Use overly complex regex on unindexed fields at high volume
  • Confuse query $regex with aggregation $regexFind

Key Takeaways

Knowledge Unlocked

Five things to remember about $regex

Use these points when writing pattern-matching queries in MongoDB.

5
Core concepts
📝 02

$regex + $options

Pattern and flags.

Syntax
🛠 03

^ and $

Start / end anchors.

Patterns
🚫 04

+$not

Exclude matches.

Exclusion
05

Index Aware

^prefix helps.

Performance

❓ Frequently Asked Questions

$regex filters documents where a string field matches a regular expression pattern. Use it in find() and $match to search by partial text, prefixes, suffixes, or complex patterns.
The syntax is { field: { $regex: "pattern", $options: "i" } }. You can also use a BSON regex literal shorthand like { field: /^pattern/i } in mongosh.
Common options: i = case insensitive, m = multiline, x = extended (ignore whitespace in pattern), s = dot matches newline. Combine them like $options: "im".
Prefix patterns anchored at the start (like ^john) can use indexes when case-sensitive and not using the i option. Leading wildcards (.*john) or case-insensitive searches often require collection scans.
$regex is a query filter that returns matching documents. $regexFind is an aggregation expression that extracts the matched substring from a field value inside a pipeline.

Continue the Operator Series

Move on to $regexFind to extract matched substrings in pipelines, or review $not for negation.

Next: $regexFind →

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