Pattern matching without using $regex operator

In MongoDB, we can do pattern matching without using the $regex operator. Simply, by using a regular expression object to specify a regular expression. Also, by using regular expression object you are allowed to use regular expression inside $ in operator.

Syntax: 

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

Here, // means to specify your search criteria in between these delimiters.

Example:

In the following examples, we are working with:

Database: w3wiki

Collection: employee

Documents: Six documents that contain the details of the employees in the form of field-value pairs.

  • Displaying details of employee who are having the word “te” in their name by using regular expression object:
db.employee.find({Name: /te/}).pretty()

Here, we are displaying the documents of those employees whose names contain the “te” string. So, we pass a regular expression(i.e., {Name: /te/}) for the Name field in the find() method. In this regular expression, // means to specify your search criteria in between these delimiters, i.e., /te/.



MongoDB – Regex

MongoDB provides the functionality to search a pattern in a string during a query by writing a regular expression. A regular expression is a generalized way to match patterns with sequences of characters. MongoDB uses Perl compatible regular expressions(PCRE) version 8.42 along with UTF-8 support. In MongoDB, we can do pattern matching in two different ways:

  • With $regex Operator
  • Without $regex Operator

Similar Reads

Pattern matching using $regex operator

This operator provides regular expression capabilities for pattern matching stings in the queries. Or in other words, this operator is used to search for the given string in the specified collection. It is helpful when we don’t know the exact field value that we are looking in the document. For example, a collection containing 3 documents i.e.,...

Pattern matching without using $regex operator

In MongoDB, we can do pattern matching without using the $regex operator. Simply, by using a regular expression object to specify a regular expression. Also, by using regular expression object you are allowed to use regular expression inside $ in operator....

Contact Us