How to Use $regex in MongoDB for Pattern Matching
In MongoDB, use the
$regex operator inside a query to find documents where a string field matches a specific pattern. The pattern is a regular expression string or object that defines the search criteria. For example, { field: { $regex: 'pattern' } } finds documents with 'field' matching 'pattern'.Syntax
The $regex operator is used inside a query to match string fields against a regular expression pattern.
- field: The name of the string field to search.
- $regex: The regular expression pattern as a string or RegExp object.
- $options (optional): Flags like
ifor case-insensitive matching.
json
{
field: { $regex: 'pattern', $options: 'i' }
}Example
This example finds all documents in the users collection where the name field contains the substring 'john' ignoring case.
mongodb
db.users.find({ name: { $regex: 'john', $options: 'i' } })Output
[
{ "_id": 1, "name": "John Doe" },
{ "_id": 2, "name": "johnny Appleseed" }
]
Common Pitfalls
Common mistakes when using $regex include:
- Not using
$options: 'i'for case-insensitive searches when needed. - Forgetting to anchor patterns if you want exact matches (e.g., use
^pattern$). - Using unescaped special characters in the pattern.
- Performance issues on large collections without indexes supporting regex.
mongodb
/* Wrong: Case-sensitive search might miss matches */ db.users.find({ name: { $regex: 'john' } }) /* Right: Case-insensitive search */ db.users.find({ name: { $regex: 'john', $options: 'i' } })
Quick Reference
| Operator | Description | Example |
|---|---|---|
| $regex | Matches strings using a regular expression | { name: { $regex: 'abc' } } |
| $options | Sets regex options like 'i' for case-insensitive | { name: { $regex: 'abc', $options: 'i' } } |
| ^ | Anchors pattern to start of string | { name: { $regex: '^abc' } } |
| $ | Anchors pattern to end of string | { name: { $regex: 'abc$' } } |
Key Takeaways
Use $regex inside a query to match string fields with patterns.
Add $options: 'i' for case-insensitive matching.
Anchor your regex with ^ and $ for exact matches.
Escape special characters in your regex pattern.
Be cautious of performance on large collections without proper indexes.