MongoDB

MongoDB Regex Match Queries

Sometimes, we do not know the value associated with the field in the document. Hence, we used the MongoDB regular expression to determine the specific matches for the document. Regular Expressions are an important element of programming that analyzes different collections of patterns, mainly the strings. We use the $regex operator as a regular expression in MongoDB to identify a pattern in a string. Regular expression features provide the $regex operator for matching a pattern of strings in queries.

How Do Regex Match Queries in MongoDB?

The $regex operator allows us to search for a specific string within a specified collection. The $regex operator allows regular expressions to be used to match pattern strings in queries. The MongoDB provides the structure of the $regex operator in this way: { <key>: { $regex: ‘pattern’, $options: ‘<options>’ } } where the key represents the column name to which the $regex is provided to match the pattern form the document. The “$options” is optional in the pattern-matching query and it contains various options which have different functionalities. We will use some of the options with the example queries. Here, we have used the database “Teachers” which is used for performing the $regex operation. We have used the insertMany query to place four documents that contain the three fields: “name”, “course” and “classes”. The query of inserting documents in the collection “Teachers” of MongoDB is given as follows:

db.Teachers.insertMany([
      {
          "Name": "Paul",
          "Course": "Web development",
          "Classes" : ["IT", "CS", "SE"]
      },
      {
          "Name": "Peter",
          "Course": "Accounts",
          "Classes" : ["SE", "BBA", "IT"]
      },
      {
          "Name": "Katherin",
          "Course": "Calculus",
          "Classes" : ["BBA", "CS", "IT"]
      },
      {          
         "Name": "Daniel",
          "Course": "Python",
          "Classes" : ["IT", "CS"]
              }
  ])

Now, all the documents are inserted into the “Teachers” collection successfully. We can easily use the fields for pattern matching with the $regex operator.

Example # 1: Using the $regex Operator in MongoDB to Match the Value.

Here, we are using the $regex operator to match the value of the position key. We have provided the field “Name” in the find() method. Then, we have provided the regular expression “{$regex: “^Paul”}” where the $regex is employed to match the value “Paul” for the field “Name”. The structure of the $regex query is provided below. The foreach() method is provided with the parameter “printjson” which shows each document given by the $regex operator query more efficiently.

db.Teachers.find({Name : {$regex: "^Paul"}}).forEach(printjson)

The document whose field “Name” is matched with the string “Paul” is retrieved in the following image of the shell:

Example # 2: Using the $regex Operator in MongoDB That Starts with the Specified Character.

Sometimes, we intend to identify the field which begins with the specific character, then $regex is used to set the selection criteria. Here, we have given a simple query where we have set the find() method which takes the field “Name”. Then, we specified the regular expression “{Name: {$regex: “P” }” to that field for pattern matching. The $regex operator matched only those names of the teachers which start with the character “p” in the documents. The document will be printed in the json format by the foreach() method.

db.Teachers.find({Name : {$regex: "P" }}).forEach(printjson)

We have only two documents printed below that matched the specified pattern of the $regex operator that the character should begin with “p”.

Example # 3: Using the $regex Operator in MongoDB That Ends with the Required Character.

As in the previous example query of the $regex operator, we have fetched the documents whose first character begins with the character specified to the $regex expression. Here, we retrieved the document whose field “Name” ends with the character “l”. The “$” symbol is used with the character “l” which ensures that the string finishes with this specific character. The regular pattern “{$regex: “l$”}}” is assigned to the $regex operator which searches for this particular pattern from the document.

db.Teachers.find({Name:{$regex:"l$"}}).pretty()

When the pattern matching query is executed, it displays only those documents whose teacher “Name” column ends up with the character “l”. The output documents are displayed in the following image of the MongoDB shell:

Example # 4: Using the $regex Operator in MongoDB with the $options Operator.

The $regex operator also provided different options which can be set using the $options operator. In this example, we used a regular expression in a case-sensitive circumstance where the “i” parameter is used in the $options operator. $options value “i” matches the upper and lower alphabet patterns in the string. The query structure is given where the position field “Course” is assigned an expression of the regular pattern matching for the case-sensitive scenarios. The expression “{$regex: “Python”,$options:’i’}” searches for the string “Python”, and the $option is used to match the lower and upper case of the string “Python”.

db.Teachers.find({Course:{$regex:"Python",$options:'i'}}).pretty()

The result displayed the document whose field “Course” comprises the case-insensitive string “Python”.

Example # 5: Using the $regex Operator in MongoDB that Matches the Value From an Array.

The principle of the regular expression can also be implemented for the arrays inside the documents. The regular expression is essential when we deal with the tags. Here, we have a regular expression query for matching the value of the tag. We have given an expression {Classes:{$regex: “IT”} to the find() method. The expression is provided with the field “Classes” which is deployed with the regular expression. The $regex operator is applied to the regular expression with the pattern “IT”. The $regex operator searches for the pattern “IT” from that array field “Classes”.

db.Teachers.find({Classes:{$regex:"IT"}})

The $regex operator returned all the documents below whose array values contained the pattern “IT”.

Example # 6: Using the $regex Operator in MongoDB Within the Aggregation Method.

The aggregation method only contains the query operator $regex along with the $match stage. So, the functionality of the $regex is performed by the $regexMatch operator. Here, we have called the aggregate() method on the “Teachers” collection. Then, we have used the $addfields which takes the attribute “results” to generate the output returned from the specified expression. The expression “$regexMatch: { input: “$Course”, regex: /Accounts/ }” is provided where the “$regexMatch” operator is used to input the field “$Course” which matched the “regex” pattern “/Accounts/”.

db.Teachers.aggregate(

[ { $addFields: { results: { $regexMatch: { input: "$Course", regex: /Accounts/ } } } } ])

Those documents whose course name is Accounts are output with the true value and the remaining document results are displayed with the false value.

Conclusion

The $regex queries are used to find patterns and characters in a string. Here, we have explored the regular expression for pattern matching by using the $regex operator in the selection criteria. Further, we have the $options which are also used with the $regex in the regular expression to match the pattern. Then, we performed the regular expression on the array and for the aggregation technique with the $regexMatch stage.

About the author

Saeed Raza

Hello geeks! I am here to guide you about your tech-related issues. My expertise revolves around Linux, Databases & Programming. Additionally, I am practicing law in Pakistan. Cheers to all of you.