0Pricing
MongoDB Academy · Lesson

Regex Queries and Pattern Matching

Learners will apply regular expressions to string fields for flexible text-pattern searches.

When You Need Pattern Matching

Sometimes you need to search for documents where a string field contains, starts with, or ends with a certain pattern—but you do not know the exact value. Simple equality filters like { name: 'Alice' } only match exact strings. Regular expressions (regex) give you flexible pattern matching against string fields in MongoDB.

MongoDB supports regex through the $regex operator or by passing a JavaScript regex literal directly in a query filter. Both approaches work, with slightly different syntax for setting options like case-insensitivity.

Basic Regex Syntax in MongoDB

There are two ways to use regex in MongoDB queries:

  • JS regex literal: { name: /alice/i } — concise, flags go after the closing slash
  • $regex operator: { name: { $regex: 'alice', $options: 'i' } } — more verbose but required when combining with other operators

Both forms produce identical results. Use the JS literal syntax for simple queries; use the $regex operator form when you need to build the pattern dynamically from a string variable or combine it with other operators on the same field.

// JS regex literal - concise
db.users.find({ name: /alice/i });
// 'i' flag = case-insensitive

// $regex operator - equivalent
db.users.find({ name: { $regex: 'alice', $options: 'i' } });

// Dynamic pattern from variable:
const searchTerm = req.query.name;
const escapedTerm = searchTerm.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // Escape special chars
db.users.find({ name: { $regex: escapedTerm, $options: 'i' } });

All lessons in this course

  1. Comparison Operators: $eq, $gt, $lt, $in
  2. Logical Operators: $and, $or, $nor, $not
  3. Element Operators and Type Checks
  4. Regex Queries and Pattern Matching
← Back to MongoDB Academy