There are two types of database categories - RDBM or relational databases like Oracle, SQL Server, etc. The other is NoSQL databases like MongoDB, CosmosDB, etc. MongoDB has become popular compared to other databases because of its simple design, simple control over the stored data, and provision for both vertical and horizontal scaling. This article explains MongoDB Regex and pattern matching with and without the $regex operator. 

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

What Is MongoDB Regex?

Regular expressions are used to match patterns. It is nothing but finding strings within documents. At times, it is unknown what the exact field value to search for while retrieving documents in a collection. To assist the retrieval of data based on pattern matching search values, one can use regular expressions. 

MongoDB provides the service to search for a pattern in a string using the regular expression during a query. It uses Perl compatible regular expressions (PCRE) version 8.42 and UTF-8 support. One can do pattern matching in MongoDB - with the $regex operator and without the $regex operator. 

Pattern Matching Using $regex Operator 

The $regex operator provides regular expression capabilities for pattern matching strings in the queries. In simpler terms, using this operator, one can search for the given string in a specific collection. If the exact field value is unknown that one is looking for in the document, this operator can turn in handy. 

Syntax:

{ <field>: { $regex: /pattern/, $options: '<options>' } }

{ <field>: { $regex: 'pattern', $options: '<options>' } }

$options:

The following <options> are available in MongoDB to use with regular expressions:

  • s - Allow the dot (.) character to match all characters, including newline characters. 
  • x - To ignore all white space characters in the $regex pattern. 
  • i - Used to match both upper and lowercase patterns in the string. 
  • m - Use ^ and $ to specifically search for ^ and $ inside the string. If these are not used, these anchors match at the string’s end or beginning.

Example: 

Display details of members who have the word senior in their position field:

db.member.find({position : {$regex : "senior"}}).pretty()

In this case, display the members' documents whose position field contains a senior string. To obtain that, pass a regular expression using the $regex operator, i.e. {$regex : “senior”} for the position field in the find() method. 

>db.member.find({position: ($regex: "senior"}}).pretty()

{

"_id" : ObjectId("6012d803fcb649933cd59833"),

"Name": "Tony",

"age" : "32",

"position": "Associated member"

}

{

_id" : ObjectId("6012d803fcb649933cd59834"),

"Name": "Bruce",

"age" : "25",

"position": "Frontend member"

}

>

Become a Data Scientist with Hands-on Training!

Data Scientist Master’s ProgramExplore Program
Become a Data Scientist with Hands-on Training!

Key Points to Remember 

  • One cannot use the $regex operator inside the $in operator. 
  • If the index of the specified field is available for case-sensitive regular expression, then MongoDB matches them to the index values. They do not utilize indexes effectively for case-sensitive regular expression queries. 
  • Using the $regex operator to add a regular expression inside a comma-separated list of a query condition is mandatory. 
  • Use the $regex operator expression with $options to use x and s options. 
  • With the latest version of MongoDB 4.0.7, one can use the $not operator with the $regex operator expression. 
  • Use the $regex operator if the Perl compatible regular expressions are not supported in JavaScript. 

Pattern Matching Without Using the $Regex Operator

It is possible to match patterns without using the $regex operator in MongoDB. To do so, use a regular expression object to specify a regular expression. Moreover, use regular expressions inside $in the operator by using regular expression objects. 

Syntax:

{ <field>: /pattern/<options> }

// means to specify the search criteria in between delimiters. 

Example:

Display details of members with the word ‘te’ in their name by using regular expression objects.

db.member.find({Name: /te/}).pretty()

Here, display the members' documents whose names contain the ‘te’ string. So, pass a regular expression, i.e. {Name: /te/} for the name field in the find() method. // is used to specify the search criteria between the delimiters, i.e.,/te/. 

>db.employee.find({Name: /te/}).pretty()

{

"_id" : ObjectId("6012d803fcb649933cd59836"),

"Name" : "Steve",

"age" : "32",

"position": "Data Analyst"

}

{

"_id" : ObjectId("6012d803fcb649933cd59838"), 

"Name": "Peter",

"age": "22",

"position": "Junior software engineer"

}

>

Conclusion

Do you know what adds value to any business? It’s the data scientists who work in the company. Data scientists are valuable to the company, from helping senior staff make better decisions to hiring candidates. Data scientists are dominating the emerging markets. With a whopping 37% growth, data science has become one of the most demanding disciplines. So, do you want to get yourself a high-paying job by becoming a data scientist? Register right away for the Professional Certificate Program in Data Science offered by Simplilearn and grab the opportunity to become popular with your work and skills. 

Our Big Data Courses Duration And Fees

Big Data Courses typically range from a few weeks to several months, with fees varying based on program and institution.

Program NameDurationFees
Post Graduate Program in Data Engineering

Cohort Starts: 25 Apr, 2024

8 Months$ 3,850