Skip to main content
The $regex operator matches documents where field terms match a regular expression pattern. This is useful for flexible pattern matching when exact values are unknown or when you need to match variations of a term.

How Regex Matching Works

Regex patterns are matched against individual tokenized terms, not the entire field value. Text fields are tokenized (split into words) during indexing, so the regex is applied to each term separately. For example, if a document contains “hello world” in a text field:
  • { $regex: "hel.*" } matches (matches the “hello” term)
  • { $regex: "hello world.*" } does NOT match (regex cannot span multiple terms)
  • { $regex: "wor.*" } matches (matches the “world” term)
For exact phrase matching across multiple words, use the $phrase operator instead.

Performance Considerations

  • Avoid leading wildcards: Patterns like ".*suffix" require scanning all terms in the index and are slow. Prefer patterns that start with literal characters.

Stemming Behavior

On fields with stemming enabled (the default), regex operates on the stemmed form of terms. For example, “running” might be stored as “run”, so a regex pattern "running.*" would not match. To use regex reliably, consider using NOSTEM on fields where you need exact pattern matching. See Text Field Options for more details.

Compatibility

Field TypeSupported
TEXTYes
U64/I64/F64No
DATENo
BOOLNo

Examples

// Match categories starting with "e"
await products.query({
  filter: {
    category: {
      $regex: "e.*",
    },
  },
});

// Match email domains (requires NOTOKENIZE field)
await users.query({
  filter: {
    email: {
      $regex: ".*@company\\.com",
    },
  },
});

// Match product codes with pattern
await products.query({
  filter: {
    sku: {
      $regex: "SKU-[0-9]{4}",
    },
  },
});