Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 70 ยท Query operators

Text Matching and Regular Expressions

Match text in MongoDB with $regex, learn which patterns can use an index, and compare it with text indexes, $text and Atlas Search for real search features.

Sooner or later someone asks for a search box. MongoDB gives you three tools for matching text, from the cheapest to the most capable: regular expressions with $regex, text indexes with $text, and Atlas Search for full search-engine features. They look similar from the outside ("find documents containing this word"), but they behave very differently when the collection grows, and picking the wrong one is a classic source of slow queries.

This lesson covers all three. The regular-expression part is runnable on the site's practice engine, a small JavaScript matcher that follows MongoDB's rules for $regex and its options. Text indexes and Atlas Search need a real MongoDB server, so their commands are read-only mongosh blocks, and I add a small toy search function so you can see what a text index does conceptually. The engine and the toy are stand-ins: they teach the ideas, but they have no real indexes, no real stemmer and none of MongoDB's performance behavior.

Three tools for text

$regex Patterns on one field. Simple, flexible, often slow.
$text Word search through a text index.
Atlas Search A full search engine next to your data.

Start with $regex, grow into the others when you need ranking.

1 / 2

$regex and its options

You have already seen the basics in Element and Evaluation Operators. A regular expression filter can be written in two ways, and both are real mongosh syntax:

JavaScript
db.cities.find({ name: { $regex: "^mar", $options: "i" } })
db.cities.find({ name: /^mar/i })

MongoDB uses a Perl-compatible dialect (PCRE), which is close to JavaScript's but not identical, so keep patterns simple. The common options are:

Option Meaning
i Case-insensitive
m ^ and $ also match at line breaks inside the string
s . also matches a newline
x Ignore whitespace and # comments in the pattern (extended)

Three rules save time. Escape special characters (., +, *, ?, (, ), [, ], $, ^) when you mean them literally, and remember that in a string you need a double backslash ("St\\. Louis"). Anchor the pattern with ^ or $ whenever you can, because an anchored pattern is both more correct and faster. And never build a pattern from raw user input: escape it first, or a user typing .* gets everything, and a badly written pattern can burn CPU.

Regular expressions also work inside $in as literals, as in { name: { $in: [/^Mar/, /^Mad/] } }, but not in the $regex operator form.

JS Options, anchors and escaping

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The first line returns nothing: without i, ^mar does not match the capital M. The unescaped ^St. matches "Stuttgart" as well, because the dot means "any character", while the escaped version finds only "St. Louis". These two mistakes, forgetting the case option and forgetting to escape, cause most regex bugs.

Which patterns can use an index

An index on a string field stores the values in sorted order, a bit like a phone book. A phone book is great for "everything starting with Mar", because those entries sit together. It is useless for "everything containing ar", because you would have to read every page. Regular expressions behave the same way:

  • A case-sensitive, anchored literal prefix such as /^Mar/ can use tight index bounds: MongoDB jumps to the start of the range and reads only the matching keys.
  • A case-insensitive pattern (/^mar/i), an unanchored pattern (/ar/) or anything starting with a wildcard cannot narrow the range. If the field is indexed, MongoDB can still scan the index keys, which is cheaper than reading documents, but it examines every key.
  • A pattern with an alternation or wildcard before the literal (/^(Mar|Mad)/, /^.ar/) generally cannot use tight bounds either.

If you need case-insensitive prefix searches, store a lowercase copy of the field (for example nameLower) and query that with an anchored pattern, or create an index with a case-insensitive collation and run the query with the same collation. Both keep the fast prefix behavior.

The next example simulates the idea. It builds 20,000 sorted keys, then counts how many keys each style of pattern has to look at. This is a model of an index, not a real MongoDB index, so the numbers show the shape of the difference, not real timings.

JS Why anchored prefixes are cheap

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The anchored prefix needs roughly fifteen binary-search steps plus one step per match, while the other two patterns walk all 20,000 keys even though they might match fewer or more names. In real MongoDB you would confirm this with explain("executionStats"), where totalKeysExamined tells the same story; see explain() and the Profiler.

Text indexes and $text

For real word search ("articles about brewing coffee"), MongoDB offers a text index. It splits the text of the indexed fields into words, lowercases them, drops common words ("the", "of") and reduces words to their stems according to a language, so brewing and brew become the same term. A collection can have only one text index, but that index can cover several fields, with weights. These are real mongosh commands and cannot run here:

JavaScript
db.articles.createIndex(
  { title: "text", body: "text" },
  { weights: { title: 10, body: 1 }, default_language: "english" }
)

// words are OR-ed; "-" excludes a word; quotes demand a phrase
db.articles.find({ $text: { $search: "coffee brew -decaf" } })
db.articles.find({ $text: { $search: "\"cold brew\"" } })

// rank by relevance
db.articles
  .find(
    { $text: { $search: "coffee brew" } },
    { title: 1, score: { $meta: "textScore" } }
  )
  .sort({ score: { $meta: "textScore" } })

What a text index does not do: match part of a word (coff finds nothing), tolerate typos, or autocomplete. A query can contain only one $text clause, and $text cannot be used with $nor. The toy below imitates the core idea, with the index weights, a tiny stop-word list and a naive stemmer. It is not MongoDB's real tokenizer, which uses proper stemmers and stop-word lists for each language.

JS A toy text index: words, stems and scores

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Look at the results: the query brewing finds the articles that say brew or brewing, because all of those words reduce to one stem. The query coffee -decaf drops the article that mentions decaf, and coff finds nothing, just like a real text index. Scores favor the documents where the words appear in the title, which is what weights does for real.

Atlas Search: when you need a search engine

If your search needs typo tolerance, autocomplete, highlighted snippets, facet counts, synonyms or per-field relevance tuning, a text index will feel limiting. Atlas Search is MongoDB's answer: a full-text search engine (built on Apache Lucene) that is integrated with Atlas clusters. You define a search index, then query it through the $search stage of an aggregation pipeline:

JavaScript
db.articles.aggregate([
  { $search: { index: "default", text: { query: "cofee", path: ["title", "body"], fuzzy: {} } } },
  { $project: { title: 1, score: { $meta: "searchScore" } } },
  { $limit: 5 }
])

The fuzzy option lets "cofee" still find "coffee". Atlas Search is a separate feature with its own index definitions and its own pricing considerations, so use it when the product really needs search-engine behavior. MongoDB Atlas Overview says more about it. For an internal tool or an admin filter, $regex on an anchored prefix, or a text index, is usually enough.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which pattern can use tight index bounds on an indexed string field?

    Only a case-sensitive pattern anchored to a literal prefix lets MongoDB jump to a key range. Case-insensitive, unanchored or wildcard-first patterns must examine every index key.
  2. 2. What is the problem with { name: { $regex: "^St." } } when you want names that start with 'St.' including the dot?

    An unescaped dot means any character. Put a backslash before the dot (in a string that is two backslashes) to match a literal dot.
  3. 3. How many text indexes can a single collection have?

    A collection can have a single text index, but that index can include several fields and per-field weights.
  4. 4. A user types 'cofee' (a typo) and expects to find 'coffee'. Which tool supports that?

    Text indexes match whole stemmed words and do not tolerate typos. Fuzzy matching is a search-engine feature offered by Atlas Search.

Summary

  • $regex (or a regex literal) matches patterns on one field; the options are i, m, s and x.
  • Escape special characters, anchor patterns where possible and never pass raw user input as a pattern.
  • Only case-sensitive patterns anchored to a literal prefix can use tight index bounds; other patterns examine every key at best.
  • Store a lowercase copy or use a case-insensitive collation index for fast case-insensitive prefix search.
  • A text index (one per collection) supports $text word search with stemming, stop words, phrases, exclusions and textScore ranking, but no partial words and no typo tolerance.
  • Atlas Search adds fuzzy matching, autocomplete, highlighting and facets through the $search stage.

Now that you can find documents, learn to change them in Updating Documents.