Regular expressions, or regex, are a useful tool that provides a pattern-matching method. If you know what particular field value you are searching for, regex can help you find data matching the sample provided. In our topics, we have already covered the basics of regex patterns and how they work. This time we will explore how the regex function is implemented in MongoDB.
$regex operator
If you want to find any specific string within the MongoDB collection, there is a special operator for it, $regex. Let's consider an example of how exactly this operator performs.
Take a look at the following collection "Employees":
[
{
"id": "mf19",
"name" : "Mark",
"surname" : "Fishman",
"department" : "IT"
},
{
"id": "mk23",
"name" : "Mary",
"surname" : "Kravitz",
"department" : "sales"
},
{
"id": "jh12",
"name" : "John",
"surname" : "Hartman",
"department" : "Sales",
},
{
"id": "jh123",
"name" : "Jill",
"surname" : "Harrison",
"department" : "it",
}
]
Suppose you want to pick names from the given collection starting with "Ma". Below is the code with the $regex command that can help you with that:
db.Employees.find( { name: { $regex: 'Ma.*'} } ).pretty()
.* is a special regex combination implying that "Ma" can be followed by any sequence of characters except line break \n (you can always consult the regex cheat sheet to choose an appropriate combination of symbols).
As you could've guessed, the result our command returns will be the following:
{
"id": "mf19",
"name" : "Mark",
"surname" : "Fishman",
"department" : "IT"
},
{
"id": "mk23"
"name" : "Mary",
"surname" : "Kravitz",
"department" : "Sales"
}
Now let's say you want to find an employee with the exact id combination "jh12". In this case, you should apply the following command:
db.Employees.find( { id: { $regex: 'jh12'} } ).pretty()
It will return two records: id 'jh12' and id 'jh123'.
So what regex expression should you apply to get the precise id of John Hartman? Use the following line of code:
db.Employees.find( { id: { $regex: '^jh12$'} } ).pretty()
These two characters, ^ and $, define the borders of the word. ^ affirms that the string starts with a certain symbol and $ makes sure that it ends with a certain symbol. This time we will get only the requested id "jh12".
$options operator
Very often you will want to avoid case sensitivity in your search, sometimes, to overcome some restrictions of regex or to apply a search pattern for multiple lines. In these cases, the $options keyword becomes very useful. In the table below you can find four indicators, that can be used together with $options.
| option | description |
| i | helps to avoid case sensitivity in the @regex search. |
| m | when searching for patterns with ^ or $ symbols, this option returns multiple lines if the search pattern exists in more than one line. |
| s | allows regex dot symbol . to match all characters including \n. |
| x | ignores all white space characters in a regex pattern unless escaped (also ignores comments, denoted by the # character). |
Let's consider an example with the i option within the regex expression as it is the most often used one. In our Employee collection department names are written differently. This time we want to extract all employees from the IT department.
In order not to miss any employees, we should write the following request:
db.Employee.find( {department: {$regex: 'it', $options: 'i'}} ).pretty()
By adding this i option we make sure that all records with it, IT, It or iT will be returned, so we won't miss a record.
Pattern matching search without $regex
In MongoDB syntax, there is an alternative way of searching for patterns using // construction.
The code looks as follows:
db.Name.find( {field: /pattern/<options> }
Our request from above can be re-written in the following ways:
db.Employees.find( { name: /Ma.*/ } ).pretty()
db.Employees.find( { id: /^jh12$/ } ).pretty()
db.Employee.find( {department: /it/i} ).pretty()
Looks a lot easier, doesn't it?
Conclusion
This time we've covered a useful topic about regular expressions and how they can be applied in MongoDB. We've got acquainted with regex and options operators and learned how to write basic search requests with some regex patterns. Also, we've studied an alternative way of applying regular expressions in MongoDB.
Sometimes, when you see regex in use, they seem to be complicated and confusing. But do not worry, if you complete several tasks with them, you will get better at understanding how they work. So, do not waste your time and get down to practice!