MongoDB Regex Queries
Exact matches work well when you know the full value. Real searches often work with partial words, such as every name that starts with "Ra" or every email that ends with "example.com". A regular expression, shortened to regex, describes a text pattern, and MongoDB uses it to find all strings that fit the pattern.
The Pattern Stencil Picture
A regex acts like a stencil. You place the stencil over each text value, and only the values that fit the cut-out shape come through.
Pattern: ^Ra
Names: Rahul ---> passes (starts with Ra)
Ravi ---> passes
Meera ---> blocked
Sara ---> blocked (Ra appears, but not at the start)Sample Data
db.users.insertMany([
{ name: "Rahul", email: "rahul@example.com" },
{ name: "Ravi", email: "ravi@school.org" },
{ name: "Meera", email: "meera@example.com" },
{ name: "Sara", email: "sara@example.com" },
{ name: "anita", email: "anita@work.net" }
])Write a Regex Query
MongoDB accepts a regex in two forms. The slash form looks like JavaScript:
db.users.find({ name: /^Ra/ })The operator form uses $regex and works well when the pattern comes from a variable:
db.users.find({ name: { $regex: "^Ra" } })Both queries return Rahul and Ravi.
Common Pattern Symbols
| Symbol | Meaning | Example |
|---|---|---|
| ^ | Start of the text | ^Ra matches Rahul |
| $ | End of the text | com$ matches example.com |
| . | Any single character | R.vi matches Ravi |
| .* | Any number of any characters | a.*a matches Sara |
| [abc] | One character from the list | [RS]a matches Ra and Sa |
| + | One or more of the previous item | e+ matches e, ee, eee |
| \d | One digit | \d\d matches 25 |
Practical Examples
Text Ends with a Word
db.users.find({ email: /example\.com$/ })The backslash before the dot makes it a real dot. A plain dot would match any character. This query returns Rahul, Meera, and Sara.
Text Contains a Word
db.users.find({ name: /ar/ })The query returns Sara, because the letters "ar" appear inside the name.
Ignore Uppercase and Lowercase
The option i turns off case sensitivity:
db.users.find({ name: /^A/i })
db.users.find({ name: { $regex: "^A", $options: "i" } })Both queries find "anita", even though the pattern uses a capital A.
Exclude a Pattern
db.users.find({ name: { $not: /^R/ } })The result lists every user whose name does not start with R.
Combine Patterns
db.users.find({ $or: [ { name: /^R/ }, { email: /@work\.net$/ } ] })Regex Options
iignores case.mlets ^ and $ match at the start and end of each line in multi-line text.xignores spaces inside the pattern for easier reading.slets the dot match a new line character.
Regex and Speed
Regex searches can slow down on large collections. The pattern shape decides how much work MongoDB does.
| Pattern Type | Speed with an Index |
|---|---|
| Case-sensitive prefix, such as ^Ra | Fast. MongoDB walks a narrow range of the index. |
| Case-insensitive or no prefix, such as /ar/i | Slower. MongoDB scans the whole index or collection. |
| Starts with .* wildcard | Slowest. MongoDB cannot narrow the search. |
Tips for Faster Searches
- Anchor patterns with ^ whenever the search starts at the beginning of the text.
- Create an index on the field that regex queries use.
- Store a lowercase copy of a field when users search without caring about case.
- Switch to a text index or Atlas Search for word-based searching across large amounts of text.
Regex Inside Aggregation
The $regexMatch operator returns true or false for each document and fits inside pipeline stages:
db.users.aggregate([
{ $addFields: { isExample: { $regexMatch: { input: "$email", regex: /example\.com$/ } } } }
])Safety Reminder
Applications that build patterns from user input must escape special characters first. A visitor who types a symbol such as .* can otherwise change the meaning of the search or trigger a slow query. Most programming languages provide a helper function that escapes text for regex use.
Summary
Regex queries search text by pattern instead of exact value. The slash form and the $regex operator both work, and the i option ignores case. Anchored prefix patterns run quickly with an index, while patterns that start with wildcards scan far more data. Escaping user input keeps searches predictable and safe.
