MongoDB Regular Expression ($option & $regex) with Examples

After MongoDB Capped Collection, today we are going to see a new concept MongoDB Regular Expression for pattern maching. Here, we will see the MongoDB regex and option operators with examples. Along with this, we will learn how to use regex in array element in MongoDB and query optimization.

MongoDB regular expression

MongoDB Regular Expression ($option & $regex) with Examples

1. What is MongoDB Regular Expression?

MongoDB regular expression are use for matching different patterns. This is useful for finding strings within documents. It may happen sometime that you may not know what field value you should search for in documents for a specific collection. Hence, we can use regular expression in MongoDB for finding out some unique matches for any document.

i. MongoDB $regex

MongoDB regex operator is used to search for strings in collection. Now we will take an example to understand about regex operator:

We will take an example table with two fields as “Employee_id” and “Employee_name”.

Employee_idEmployee_name
 20 abc
 12 def
 3 ghi
 2 jkl
 89 mno
 7 pqr

Now we will write the code to find “Employee_name” with initials as “ab”.

db.Employee.find({Employee_name : {$regex: "ab" }}).forEach(printjson)

Here, printjson is used to print each document which is returned by the query in a better way.

If suppose your collection has documents with Employee_name as “abc123”. If you entered the search criteria as “abc12”, it will also return all documents with name as “abc123”. So if you just wanted to make a query to search for “abc12” then we have to use exact pattern matching. For doing exact pattern matching we use ^ and $ character. We will add ^ character at the beginning and $ at the end of the string.

Employee_idEmployee_name
 20 abc
 12 def
 3 abc12
 2 abc123
 89 mno
 7 abc12
 6 abc12
db.Employee.find({Employee_name : {$regex: "^abc12$"}}).forEach(printjson)

Here ^ is used to denote that a string starts with a certain character and $ is used to ensure that a string ends with a certain character.

Do you know how MongoDB Create Database? 

ii. MongoDB $options

When you want to provide some additional options in regex operator then you will use $options keyword. Suppose you want to search all documents which are having “ab” in their Employee_name, irrespective of whether it is case sensitive or insensitive. For searching a result without considering case sensitivity in that we use $options.

For this we will consider the following documents in our collection.

Employee_idEmployee_name
 20 abc
 12 def
 3 ABC12
 2 abc123
 89 mno
 7 ABc12
 6 Abc12
db.Employee.find({Employee_name:{$regex: "ab",$options:'i'}}).forEach(printjson)

Here $options with ‘i’ parameter specifies that we want to carry out search without considering upper or lower case. Same will happen with our example in which “ab” will be searched whether it is upper or lower case.

Also, see – How to generate MongoDB Auto Increment Sequence

We can also perform pattern matching without using MongoDB regex operator. The example below will give us how to do this:

db.Employee.find({Employee_name: /ab/'}).forEach(printjson)

Here “//” specifies that our search criteria is within these delimiters.

Fetching last ‘n’ documents from a collection

There are various ways to get last n documents from a collection.

Let’s see the example to understand one way of getting last n documents in a collection.

Employee_idEmployee_name
 20 abc
 12 def
 3 abc12
 2 abc123
 89 mno
 7 abc12
 6 abc12
db.Employee.find().sort({_id:-1}).limit(2).forEach(printjson)

Here limit is used to display the number of records you want. Here it is set as 2 so it will search for last 2 documents. And -1 is used to sort the document in descending order.

2. How to Use regex for array element in MongoDB?

We can use MongoDB regular expression in array fields too. When we implement the functionality of tags then it is important to have them starting from the word MongoDB in order to search for all posts having this tag. We will look at the code for the above statement now:

> db.example.find({tags:{$regex:"Mongo"}}).pretty();
{
     "_id" : ObjectId("590e5b7bd774a89bd3a0c5fb"),
     "blog_text" : "MongoDB uses regular expression",
     "tags" : [
           "MongoDB",
           "regular",
           "expression"
     ]
}
> db.example.find({tags:{$regex:"MongoDB"}}).pretty();
{
     "_id" : ObjectId("590e5b7bd774a89bd3a0c5fb"),
     "blog_text" : "MongoDB uses regular expression",
     "tags" : [
           "MongoDB",
           "regular",
           "expression"
     ]
}
>

Follow this link to know Covered and Analyzing Query in MongoDB

3. MongoDB Query Optimization

We can optimize MongoDB regular expression queries just like we do in relational database. Following are some of the concepts used in MongoDB for query optimization:

  1. We can create database indexes on the document fields so that the MongoDB query will make use of these indexed values to match regular expression. This makes search and data retrieval from the collection very fast as compared to traditional regular expression scanning.
  2. Create a query with regular expression as a prefix expression where all the matches are meant to begin with a particular string character.

For eg: if the regex expression is ^example, then such a query will search only those strings that begin with example.

4. Summary

Hence, we have studied about MongoDB regular expressions for pattern matching with $regex and $option. Along with this, we learned hos to use regex for array element and query optimization.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.