MongoDB $regex Operator

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

What Is $regex?

$regex is a MongoDB query operator that keeps documents whose string field matches a regular expression. Use it in find() or $match for partial text, prefixes, suffixes, and simple patterns.

Remember
$regex = field matches this pattern?

{ field: { $regex: "pattern", $options: "i" } }

// mongosh shorthand
{ field: /pattern/i }

^Note  → starts with Note
book$  → ends with book
ash    → contains ash
i      → case insensitive

query filter — not an aggregation extract
(for extract → $regexFind)
UsePrefer
Filter docs by pattern$regex
Extract match in a pipeline$regexFind
Full-text search$text

How to Use $regex in MongoDB

Write a pattern against a string field, then optionally add flags.

  1. Choose the string field to test (for example name).
  2. Pass the pattern with { $regex: "..." } (or a /.../ literal).
  3. Add $options when you need flags such as "i".
  4. Prefer anchored prefixes (^...) when you care about index use.
PieceRequired?Role
FieldYesString field to match
$regex patternYesRegular expression text
$optionsNoFlags like i, m, s, x

Pseudocode

Pseudocode
for each document:
    text = document.field
    if text is a string AND text matches pattern (with options):
        keep document
    else:
        skip

Cheat Sheet

Keep these facts handy while writing pattern filters.

TopicDetail
TypeQuery operator (find / $match)
Syntax{ field: { $regex: "...", $options: "i" } }
Shorthand{ field: /pattern/i }
Common flagsi case · m multiline · s dotall
Prefix tip^Note can use an index
vs $regexFindFilter docs vs extract match
Sampleash + i matches "Asha"

Live Preview

Test simple patterns against sample product names (same idea as $regex).

Simulates { name: { $regex: "...", $options: "..." } } on three products.

Result
pattern = /ash/i

Notebook  → match
Pen Set   → no
Flashcard → match

kept → Notebook, Flashcard

Worked Walkthrough — Names with “ash”

Three products sit in a catalog. We want names that contain ash, ignoring case.

Calculation
Documents:
  Notebook
  Pen Set
  Flashcard

Filter:
  { name: { $regex: "ash", $options: "i" } }

Notebook  → contains "ash"  ✓
Pen Set   → no "ash"        ✗
Flashcard → contains "ash"  ✓

Result → Notebook, Flashcard

MongoDB Examples

We use three products. First insert them, then filter with $regex, then show a prefix match. Run these in mongosh after inserting the sample data once.

Example 1 — Sample Data

Imagine three products: Notebook, Pen Set, and Flashcard. We save them in a collection named products.

mongosh
db.products.insertMany([
  { _id: 1, name: "Notebook" },
  { _id: 2, name: "Pen Set" },
  { _id: 3, name: "Flashcard" }
]);

How the Data Is Stored in MongoDB

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

mongosh
db.products.find()

Read those documents like this:

Field in MongoDBValuesPlain English
_id1, 2, 3Document ids
nameNotebook / Pen Set / FlashcardString field for $regex
Picture
"ash" + option i

Notebook   ✓  (…ash…)
Pen Set    ✗
Flashcard  ✓  (…ash…)

How It Works

  1. Insert once. insertMany adds three product documents.
  2. Store plain strings. name is what $regex will test.
  3. find() shows all three. Filtering comes next.

Example 2 — Contains (Case-Insensitive)

Goal: return products whose name contains ash, ignoring case.

mongosh
db.products.find({
  name: { $regex: "ash", $options: "i" }
});

How It Works

  1. Same three products. Still using the documents from Example 1.
  2. Apply the pattern. $regex: "ash" looks for that substring.
  3. Ignore case. $options: "i" keeps both Notebook and Flashcard.

Example 3 — Prefix Match

Same catalog, but keep only names that start with Note using ^.

mongosh
db.products.find({
  name: { $regex: "^Note" }
});

// shorthand in mongosh:
// db.products.find({ name: /^Note/ });

How It Works

  1. Anchor at the start. ^ means “must begin with”.
  2. Match Note… Only Notebook starts with Note.
  3. Index-friendly shape. Prefix patterns (without i) are the best $regex form for indexes.

Edge Cases & Pitfalls

Check these before shipping regex filters to production.

index

Leading wildcards are slow

Patterns like .*ash or unanchored contains often scan the collection. Prefer ^prefix when you can.

case

Option i has a cost

Case-insensitive $regex usually cannot use a normal index efficiently. Use it when you truly need it.

escape

Escape special characters

Characters like ., *, +, and ( are regex metacharacters. Escape user input before building a pattern.

vs find

Filter ≠ extract

$regex decides which documents to keep. To pull out the matched text, use $regexFind.

Performance Notes

ApproachCostBest for
^prefix (no i)Can use indexStarts-with filters
Contains / iOften COLLSCANSmall collections / rare queries
$text + text indexIndex-backed searchFull-text search needs

Regex is flexible but easy to make expensive. Anchor prefixes when possible, and consider $text for real search workloads.

Key Takeaways

  • Role: keep docs whose string field matches a pattern.
  • Flags: use $options (for example "i").
  • Speed: ^prefix helps indexes; contains / i often does not.
  • Sample: ash + i → Notebook, Flashcard.

One line: $regex answers “does this string field match my pattern?”—and returns the matching documents.

Frequently Asked Questions

$regex filters documents where a string field matches a regular expression pattern. Use it in find() and $match for partial text, prefixes, suffixes, or richer patterns.
Use { field: { $regex: "pattern", $options: "i" } }. In mongosh you can also write a RegExp literal such as { field: /^pattern/i }.
Common flags: i = case insensitive, m = multiline, x = extended (ignore unescaped whitespace in the pattern), s = dot matches newline. Combine them like "im".
Case-sensitive prefix patterns anchored at the start (like ^Note) can use an index. Leading wildcards or the i option often force a collection scan.
$regex is a query filter that returns matching documents. $regexFind is an aggregation expression that extracts match details from a string inside a pipeline.
Use $text for full-text search with a text index. Use $regex for simple pattern checks on one field when a text index is not the right tool.

Next: $regexFind

Pull match details from a string inside an aggregation pipeline.

$regexFind tutorial →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

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