Updated February 28, 2023
Introduction to MongoDB $regex
Every Document stored in MongoDB collections, has a pattern, this pattern can be recognized and used and using MongoDB’s $regex operator, these patterns can be identified. To carry out this operation, MongoDB uses a Regular Expression Engine written in C and is known as Perl Compatible Regular Expressions a.k.a “PCRE”. These regular expressions are one of the most widely used tools in programming, related to strings. This establishes that every string can be connected in a way through a pattern, now this pattern can be recognized and used to boost search for string data values.
Syntax
Now that we have understood, what this $regex operator is, let us understand the basic syntax. With MongoDB’s $regex, we have three simple syntaxes to choose from, below are these syntaxes:
Syntax #1
{ <field>: { $regex : /pattern/<options> } }
Syntax #2
{ <field>: { $regex : 'pattern', $options: '<options>' } }
Syntax #3
{ <field>: { $regex : /pattern/, $options: '<options>' } }
Breaking the above syntaxes, the <field> is the key-value or the name of the field. Then the keyword, $regex, intends to implement the operator. /pattern/ is one of the most important parts of the syntax as it is the point of understanding. The pattern here passed will be used for a search operation.
Out of the above three syntaxes, the first one is the simplest and easy, where we only specify a field name and a simple pattern we intend to find. Second and third syntaxes are quite similar to the minor differences in how the intended pattern is passed.
How $regex Works in MongoDB?
Understanding how $regex works are crucial to understand it deeply and implement these powerful MongoDB operators in real-time applications. The regex is a regular expression. MongoDB implements the Perl Compatible Regular Expressions for $regex. $regex operator simply picks the pattern that we provide and based on the options, it searches for the pattern and returns documents. We will implement the above syntaxes for a better understanding of the options.
Also, comparing the working of $regex, we might think and questions its similarity with simple text search. Still, we must understand that the text search over mongodb data does not return efficient results in a larger dataset. Text search probably returns a single document and lacks the support of the skip parameter. MongoDB’s such operators make the NoSQL database easy to work with and implement. $regex makes the data retrieving operations easy.
Examples of MongoDB $regex
Following are the examples are given below:
Example #1
As we have learned what regex operator is, how it works and its proper syntax, let’s dive into practical implementation. With the following examples, we will understand the real-time usage of the operator. Below is a screenshot of a simple collection created with the name of regex, with string data to implement the regex examples.
db.regex.find()
Now that we have our data ready let’s build our first query.
db.regex.find({text:{ $regex: "sample"}})
The above query will execute a simple search operation, using the basic find command. Later we have our text, which is the name of the field or to say the key. Followed by the $regex operator being passed along with the parameter. The parameter here is a simple string, “sample”. Upon execution, the above query will return each and every document that consists of the pattern string, meaning it will return every document that has sample word in it. Refer to the below screenshot for a proper understanding of the output:
Example #2
Moving ahead, we will implement the next type of syntax with our second example. Our next example will not be a complete string but a single alphabet, along with an option. Refer to the below query:
db.regex.find({text: { $regex: /^J/}})
db.regex.find({text: { $regex: /^J/, $options: 'm'}})
Comparing to the first query, the second query is almost similar to the difference between the added option and the pattern. Here, we intend to find every document, that holds any word, that beings with the alphabet J. Refer below screenshot for output.
Upon executing the second query, the results are of two documents that fulfil the passed parameter. But in the screenshot, we can see the clear difference between the usage of the options: ‘m’. It is common to have and store string values with multiple lines, which impacts the results. As shown in the screenshot, the first query, without options m, only return document that consists of the pattern, in a single line, without any disruption. While the second query, upon execution, returns every single document that has a word starting with J, regardless of the line or any other factor. This explains the need for the option.
Example #3
We have understood the real-time implementation of the $regex operator syntax that we studied; we will now learn about another important option. We often store various data; differences can be based on the lower case or upper case, a number of lines, etc. Our next example will demonstrate the working of an option that does not distinguish between upper and lower cases, which in better results.
For example, we have inserted a document with an upper case word, following is the solution query:
db.regex.find({text: {$regex :"sample", $options: 'i'}})
By adding an option as I, we intend to pass an argument that the returning result should consist of upper and lower case words. We attempt to execute a query that will return every document that holds the “sample” word. Refer to the below attached screenshot for proper output.
Our query has returned every document with the word, sample, regardless of its condition. We have a document with lower case letters as well as upper case.
Conclusion
MongoDB’s $regex operator provides an easy way to deal with the string data types. Whatever the condition, the regular expression will provide a useful output, based on the passed parameter. Our examples explained the need for options and how it has an impact. MongoDB’s $regex operator can result in easy data handling and fast operations.
Recommended Articles
This is a guide to MongoDB $regex. Here we also discuss the syntax and parameters along with how $regex works in MongoDB?. You may also have a look at the following articles to learn more –