MongoDB

How to use $regex operator in MongoDB

MongoDB is a NoSQL database that stores documents in key-value pairs. In MongoDB, several operators tend to retrieve data by matching the exact value of the field and then display the result based on that match. Apart from these exact match operators, MongoDB provides support for partial match operators and is named as $regex in MongoDB. The $regex operator helps to match part of a value and then displays the result based on that partial tie. $regex operator is quite helpful when you do not know the exact value of a field or if you do not want to write the complete value of a field.

Knowing the importance of the $regex operator, this guide is compiled to briefly explain the usage of the $regex operator in MongoDB.

How $regex operator works

The syntax of $regex operator is given below:

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

Or:

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

Both the syntaxes work for the $regex operator; however, it is recommended to use the first syntax to get full access to options of $regex. As it is noticed that few options do not work with the second syntax.

pattern: This entity refers to the part of the value that you want to search for a field

options: The options in the $regex operator extend the usage of this operator and a more refined output can be obtained in this case.

Prerequisites

Before practicing the examples, it is required to have the following MongoDB related instances to be present in your system:

MongoDB database: In this guide, a “linuxhint” named database will be used

Collection of that database: The collection associated with the “linuxhint” database is named “employees” in this tutorial

How to use the $regex operator in MongoDB

In our case, the following content resides in the “employees” collection of “linuxhint” database:

> db.employees.find().pretty()

Text Description automatically generated

This section contains examples that explain the usage of $regex from basic to advanced level in MongoDB.

Example 1: Use of $regex operator to match a pattern

The command given below will check for the “Lin” pattern in the “distro” field. Any field value that contains the “Lin” keyword in its value gets the match. Finally, the documents containing that field will be displayed:

> db.employees.find({distro: {$regex: /Lin/}}).pretty()

Text Description automatically generated

Using $regex with “i” option

Generally, the $regex operator is case sensitive; the “i” option support of $regex operator makes it case insensitive. If we apply “i” option in the above command; the output will be same:

> db.employees.find({distro: {$regex: /LIN/, $options: "i"}}).pretty()

Text Description automatically generated

Example 2: Use $regex with caret (^) and dollar ($) sign

As the basic use of $regex matches all the fields that have the pattern in it. You can also use $regex to match the start of any string by prefixing the “caret(^)” symbol and if the “$” symbol is postfixed with characters then the $regex will search for the string that ends with those characters: The query below shows the usage of “^” with $regex:

Any value of the “distro” field that starts with characters “Li” will be retrieved and the relevant document is displayed:

> db.employees.find({distro: {$regex: /^Lin/}}).pretty()

Text Description automatically generated

The “$” sign is used after characters to match the string that ends with that character; For instance, the below-mentioned command will get the field value of “distro” that ends with “ian” and the respective documents are printed:

> db.employees.find({distro: {$regex: /ian$/}}).pretty()

A picture containing text Description automatically generated

Moreover, if we use “^” and “$” in a single pattern; then $regex will match the string that comprises of exact characters: For instance, the following regex pattern will get only “Linux” value:

> db.employees.find({distro: {$regex: /^Linux$/}}).pretty()

A screenshot of a computer Description automatically generated with medium confidence

Note: The “i” option can be used in any $regex query: in this guide “pretty()” function is used to get the clean output of Mongo queries.

Conclusion

MongoDB is a widely-used open source and belongs to the NoSQL category of databases. Due to its document-based nature, it provides a strong retrieval mechanism supported by several operators and commands. The $regex operator in MongoDB helps to match the string by only specifying a few characters. In this guide, the usage of the $regex operator in MongoDB is described in detail. It can also be used to get the string that starts or ends with a specific pattern. Mongo users can use $regex operator to find a document by using a few characters that match any of its fields.

About the author

Adnan Shabbir