MongoDB $regexFind Operator

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

What Is $regexFind?

$regexFind is a MongoDB aggregation expression that finds the first regex match inside a string and returns an object with the matched text, start index, and capture groups—or null if nothing matches.

Remember
$regexFind = extract first match (+ metadata)

{ $regexFind: {
    input: <string>,
    regex: <pattern>,
    options: "<flags>"   // optional
  }
}

success → { match, idx, captures }
no match → null

$regex      → filter documents
$regexFind  → extract from a string
$regexFindAll → every match (array)
UsePrefer
Extract first match$regexFind
Extract every match$regexFindAll
Filter docs by pattern$regex

How to Use $regexFind in MongoDB

Point at a string field, give a pattern, then read match / captures.

  1. Choose an expression stage ($addFields or $project).
  2. Set input to the string (for example "$note").
  3. Set regex to the pattern (string or RegExp).
  4. Optionally add options (such as "i") and read .match or .captures.
PieceRequired?Role
inputYesString to search
regexYesPattern to find
optionsNoFlags like i, m, s, x

Pseudocode

Pseudocode
text = evaluate(input)
if text is null or missing:
    result = null
else:
    m = first_regex_match(text, pattern, options)
    if no match:
        result = null
    else:
        result = {
          match: matched_text,
          idx: start_index,
          captures: [ group1, group2, ... ]
        }
emit { ..., field: result }

Cheat Sheet

Keep these facts handy while extracting matches in pipelines.

TopicDetail
TypeAggregation expression (not a find filter)
Syntax{ $regexFind: { input, regex, options? } }
Success shape{ match, idx, captures }
No matchnull
idxZero-based start position
vs $regexExtract vs filter documents
Sample"Order #A42" → match "#A42"

Live Preview

Watch $regexFind pull the first match from a sample note string.

Simulates { $regexFind: { input, regex } } → { match, idx, captures }.

Result
input = "Order #A42 shipped today"
regex = /#[A-Z0-9]+/

→ {
  match: "#A42",
  idx: 6,
  captures: []
}

Worked Walkthrough — Order Code

A shipping note says Order #A42 shipped today. We want the first order code that looks like # plus letters/digits.

Calculation
note = "Order #A42 shipped today"
                 ↑
              index 6

pattern = /#[A-Z0-9]+/

first match:
  match    = "#A42"
  idx      = 6
  captures = []     // no ( ) groups

with /#([A-Z0-9]+)/:
  match    = "#A42"
  captures = ["A42"]  // group 1

MongoDB Examples

We use one shipping note. First insert it, then extract the order code with $regexFind, then pull a capture group. Run these in mongosh after inserting the sample data once.

Example 1 — Sample Data

Imagine one note: Order #A42 shipped today. We save it in a collection named notes.

mongosh
db.notes.insertOne({
  _id: 1,
  note: "Order #A42 shipped today"
});

How the Data Is Stored in MongoDB

After the insert, MongoDB keeps one document in notes. Run find() to see it:

mongosh
db.notes.find()

Read that document like this:

Field in MongoDBValuePlain English
_id1Document id
note"Order #A42 shipped today"String to search
Picture
Order #A42 shipped today
      ^^^^
      match "#A42" at idx 6

How It Works

  1. Insert once. insertOne adds a single note document.
  2. Keep the full sentence. The order code is inside the string, not a separate field.
  3. find() shows the same shape. Ready for $regexFind next.

Example 2 — First Match

Goal: extract the first #CODE token into a field named found.

mongosh
db.notes.aggregate([
  {
    $addFields: {
      found: {
        $regexFind: {
          input: "$note",
          regex: "#[A-Z0-9]+"
        }
      }
    }
  }
]);

How It Works

  1. Read the note. input: "$note" is the full sentence from Example 1.
  2. Apply the pattern. #[A-Z0-9]+ means # plus one or more letters/digits.
  3. Store the object. You get match, idx, and an empty captures array.

Example 3 — Capture Group

Same note, but capture only the code part without the # using parentheses, then read captures[0].

mongosh
db.notes.aggregate([
  {
    $addFields: {
      found: {
        $regexFind: {
          input: "$note",
          regex: "#([A-Z0-9]+)"
        }
      }
    }
  },
  {
    $addFields: {
      code: { $arrayElemAt: ["$found.captures", 0] }
    }
  }
]);

How It Works

  1. Add parentheses. #([A-Z0-9]+) still matches #A42, but group 1 is A42.
  2. Fill captures. found.captures becomes ["A42"].
  3. Pick the group. $arrayElemAt: ["$found.captures", 0] writes code: "A42".

Edge Cases & Pitfalls

Check these before extracting matches in production pipelines.

null

No match → null

If the pattern misses, the whole result is null—not an empty object. Guard before reading .match.

first

Only the first match

A second code later in the string is ignored. Use $regexFindAll for every match.

filter

Not a document filter

To keep/drop documents by pattern, use $regex in find / $match.

groups

Captures need ( )

Without parentheses, captures is []. Add groups when you need a piece of the match.

Performance Notes

ApproachCostBest for
$regexFind per docRegex on one stringPulling codes / tokens
Filter then extractFewer docsLarge collections
Store parsed fieldNo recomputeHot query paths

Regex work is heavier than plain field reads. Filter early with $match when only some documents need extraction.

Key Takeaways

  • Role: extract the first regex match from a string.
  • Result: { match, idx, captures } or null.
  • vs $regex: extract in aggregation vs filter in queries.
  • Sample: "#A42" at idx 6; capture "A42".

One line: $regexFind answers “what is the first regex match in this string, and where is it?”

Frequently Asked Questions

$regexFind searches a string for the first regular expression match and returns an object with match (matched text), idx (start index), and captures (capture groups). If nothing matches, it returns null.
Use { $regexFind: { input: <string>, regex: <pattern>, options: <options> } }. Place it inside stages such as $addFields or $project. The options field is optional.
On a match: { match: "...", idx: <number>, captures: [...] }. On no match: null. idx is the zero-based start position of the match.
$regex is a query filter that keeps or drops whole documents. $regexFind is an aggregation expression that extracts the first match (and metadata) from a string field.
$regexFind returns only the first match as one object (or null). $regexFindAll returns an array of all matches.
Parentheses in the pattern fill the captures array. For example, /#([A-Z0-9]+)/ on "Order #A42" yields match "#A42" and captures ["A42"].

Next: $regexFindAll

Collect every regex match from a string into an array.

$regexFindAll 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