MongoDB Regular Expression โ€“ $regex and $options with Examples

post

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_idEmployee_name
20abc
12def
3ghi
2jkl
89mno
7pqr

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_idEmployee_name
20abc
12def
3ABC12
2abc123
89mno
7ABc12
6Abc12

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" } })


Share This Job:

Write A Comment

    No Comments