MongoDB Regular Expression โ $regex and $options with Examples
Today weโll dive into a new and practical topic: MongoDB Regular Expressions โ a powerful feature for pattern matching in database queries.
๐ What is a MongoDB Regular Expression?
In MongoDB, regular expressions are used to match patterns within string values. This is helpful when youโre searching for documents but donโt know the exact value you're looking for.
For example, if you're unsure of the full name but know part of it, regex helps in finding matching entries.
1. ๐ $regex Operator in MongoDB
The $regex operator lets you search for specific string patterns in a collection.
โ Example:
Letโs say we have a collection named Employee with the following documents:
| Employee_id | Employee_name |
|---|---|
| 20 | abc |
| 12 | def |
| 3 | ghi |
| 2 | jkl |
| 89 | mno |
| 7 | pqr |
To find employees whose names start with "ab", use:
db.Employee.find({ Employee_name: { $regex: "ab" } }).forEach(printjson)
๐ printjson simply formats the output for better readability.
Now, letโs say some records have Employee_name as "abc123" and you only want exact matches for "abc12". Use anchors (^ and $) for exact pattern matching:
db.Employee.find({ Employee_name: { $regex: "^abc12$" } }).forEach(printjson)
^ โ String must start with this pattern
$ โ String must end with this pattern
2. โ๏ธ $options in MongoDB Regex
Use $options to define additional behaviors for your regex. One popular use is case-insensitive search.
โ Example:
Letโs update our collection with names like:
| Employee_id | Employee_name |
|---|---|
| 20 | abc |
| 12 | def |
| 3 | ABC12 |
| 2 | abc123 |
| 89 | mno |
| 7 | ABc12 |
| 6 | Abc12 |
Now, to search for "ab" regardless of case:
db.Employee.find({ Employee_name: { $regex: "ab", $options: 'i' } }).forEach(printjson)
๐ $options: 'i' tells MongoDB to ignore case sensitivity.
Alternatively, you can use shorthand regex notation:
db.Employee.find({ Employee_name: /ab/i }).forEach(printjson)
3. ๐ฆ Fetching the Last โnโ Documents
To get the last n documents from a collection, sort them in descending order by _id and apply .limit().
โ Example:
db.Employee.find().sort({ _id: -1 }).limit(2).forEach(printjson)
sort({_id: -1}) โ Descending order
limit(2) โ Fetch only 2 latest documents
4. ๐ Using Regex on Array Elements
Regex can also be used to match elements inside array fields.
Suppose we have a blog document:
{ "_id": ObjectId("..."), "blog_text": "MongoDB uses regular expression", "tags": ["MongoDB", "regular", "expression"] }
To find all documents with tags containing "Mongo":
db.example.find({ tags: { $regex: "Mongo" } }).pretty()
To find tags that match exactly "MongoDB":
db.example.find({ tags: { $regex: "MongoDB" } }).pretty()
โก MongoDB Regex Query Optimization
Just like traditional databases, MongoDB queries using regex can be optimized for better performance:
Optimization Tips:
Use Indexes
Apply indexes on fields used with regex to make searches faster.
Use Anchored Regex
Queries starting with ^ (prefix regex) are faster because MongoDB can leverage indexes.
This pattern tells MongoDB to match strings starting with "example".
โ Summary
At DebugShala, youโve learned:
How to use $regex for pattern matching in MongoDB
How to enhance regex searches using $options
Ways to apply regex to array fields
How to fetch last n documents efficiently
Tips for optimizing regex queries
Regular expressions in MongoDB are a great tool for performing flexible searches, and when optimized properly, they make querying both powerful and efficient.
db.collection.find({ field: { $regex: "^example" } })
Write A Comment
No Comments