Table of contents
1.
Introduction
2.
What is MongoDB?
3.
Regex Operator
4.
Pattern Matching without Regex Operator
5.
Pattern Matching with Regex Operator
6.
Frequently Asked Questions
6.1.
How can we perform a case-insensitive search using Regex in MongoDB?
6.2.
How can we escape special characters in Regex patterns?
6.3.
What are the limitations of Regex in MongoDB?
7.
Conclusion
Last Updated: Mar 27, 2024
Easy

Regex in Mongodb

Author Aayush Sharma
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

MongoDB is a very popular NoSQL database management system that stores data in the form of JSON-like documents with key-value pairs. One powerful tool in MongoDB is the Regex method.

regex in mongodb

In this blog, we will discuss Regex in MongoDB. We will discuss MongoDB and Regex Operator in detail. We will also discuss different cases of pattern matching, one using Regex and one without Regex. In the end, we will conclude by discussing some frequently asked questions.

What is MongoDB?

MongoDB is a very popular and open-source NoSQL database management system. Unlike traditional database systems, which store data in tables and columns, MongoDB stores data in JSON-like format. This allows it to become more flexible in keeping different types of data. Developers can easily retrieve and store all data types without sticking to a predefined data format.

mongodb logo

MongoDB supports a large number of query operators. This makes it easy to perform many operations on data like conditional searches, aggregation, etc. MongoDB also supports operators like Regex, which we will discuss in further sections.

Being an open-source software, MongoDB also has a large community of developers. This makes it easy for beginners to learn about MongoDB. MongoDB also boasts robust security features, which makes it an excellent choice for developing financial applications.

Having all these features, MongoDB has now become a great choice for developers to build various applications. These applications include banking systems, e-commerce platforms, mobile and PC applications, IoT devices, etc. Qualities like versatility, scalability, fault tolerance, and flexibility have made MongoDB one of the most popular NoSQL databases in today's industry.

Regex Operator

The Regex (Regular Expression) operator is a helpful tool in MongoDB. It allows the users to perform pattern matching in a string. The Regex operator allows searching patterns easily from the data stored in the MongoDB collections.

The syntax to use the Regex function in MongoDB is given below.

Syntax

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

OR

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

 

$options:

The options parameter can be used with MongoDB to customize our Regex searches in MongoDB. Some options' variables to use in Regular Expression are shown below in a tabular format.

 

Option

 

Functionality

 

 

i

This option performs Case-Insensitive(lowercase and uppercase letters are treated as one) Regular Expression Match using Regex.

 

m

This option includes anchors like ^ and $, matched at the beginning or end of each line for strings with multiline values.

 

x

This option is used when we want to ignore all the white space characters in the $regex pattern.

 

s

This option allows the "." character to match all the characters, including the newline character in the regex pattern.

 

In the following sections, we will see some examples of pattern matching. We will see one example using the Regex function and one without using the Regex function to see the differences between them.

Pattern Matching without Regex Operator

This section will show an example of pattern matching in MongoDB without using the Regex operator.

This blog will use my database and the below collection to run MongoDB queries.
 

Database

db.users.insertMany([
{
	name: "Rahul",
	age: 30,
	email: "rahul@gmail.com",
	status: "active"
},
{
	name: "Raghav",
	age: 25,
	email: "raghav@gmail.com",
	status: "inactive"
},
{
	name: "Priya",
	age: 40,
	email: "priya@gmail.com",
	status: "active"
}
])

We need to follow the following steps to search patterns in MongoDB without Regex.

First, we need to state the field name we want to perform pattern searching. Then we must clearly state the pattern we wish to search in the string. For example, if we need to find a line containing Ra in the name field, we must follow the following syntax.

 

Syntax

db.users.find({name:/Ra/})

Output

output

Explanation

Since both "Rahul" and "Raghav" have the string Ra present in them, we get two objects in the console.

Pattern Matching with Regex Operator

In this section, we will look at the method of pattern matching using the Regex Operator.

Database

db.users.insertMany([
{
	name: "Rahul",
	age: 30,
	email: "rahul@gmail.com",
	status: "active"
},
{
	name: "Raghav",
	age: 25,
	email: "raghav@gmail.com",
	status: "inactive"
},
{
	name: "Priya",
	age: 40,
	email: "priya@gmail.com",
	status: "active"
}
])

Let's say we want to find an entry containing the string "Rahul" in the name field, but the name starts with the string "Rahul".

 

Syntax

db.users.find({ name: { $regex: '^Rahul' } })

Output

output

Explanation

Since only the entry "Rahul" starts with the string rahul, we only get a single entry as a result.

Frequently Asked Questions

How can we perform a case-insensitive search using Regex in MongoDB?

To perform a case-insensitive search using Regex, we can set the "$options" parameter to "i." By setting the options parameter to "i," we can perform a case-insensitive search using Regex in MongoDB.

How can we escape special characters in Regex patterns?

Like most programming languages like C and C++, we can use the backslash symbol ("\") to escape special characters in regex patterns. We can place the backslash before the unique character to escape special characters in Regex.

What are the limitations of Regex in MongoDB?

The regex function is resource intensive and requires a lot of computational power for large datasets and patterns. Hence, we should consider these limitations while using Regex functions in MongoDB.

Conclusion

In this article, we discussed the Regex Operator in MongoDB. We discussed MongoDB and the Regex operator in brief. We also discussed pattern matching examples, one using the Regex operator and one without using the Regex operator. In the end, we concluded by discussing some frequently asked questions.

So now that you know about Regex in MongoDB, you can refer to similar articles.
 

You may refer to our Guided Path on Code Studios for enhancing your skill set on DSA, Competitive Programming, System Design, etc. Check out essential interview questions, practice our available mock tests, look at the interview bundle for interview preparations, and so much more!

Happy Learning!

Live masterclass