$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)
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 Type | Supported |
|---|---|
| TEXT | Yes |
| U64/I64/F64 | No |
| DATE | No |
| BOOL | No |
Examples
- TypeScript
- Redis CLI