MongoDB Regular Expression - MongoDB

What is the use of regular expressions in MongoDB?

Regular Expressions are often used in all the languages to search for a pattern or word in any string. MongoDB also provides regular expression functionality for string pattern matching using $regex operator. MongoDB uses PCRE (Perl Compatible Regular Expression) as regular expression language.

Unlike text search, there is no need to do any configuration or command to use regular expressions.
Consider below document structure under posts collection containing post text and its tags

Using regex Expression

Below regex query will search for all the posts consisting of string wisdomjobs in it

Same query can also be written as

Using regex Expression with Case Insensitive

$options parameter with value $i can be used to make the search case insensitive. Below command will look for strings which have the word wisdomjobs, irrespective of smaller or capital case

One of the results returned from this query is the below document which includes the word wisdomjobs in different cases

Using regex for Array Elements

Regex concept can also be used on array field which is particularly very important when the functionality of tags is implemented. Therefore, if you want to search for all the posts which have tags beginning from the word tutorial (either tutorial or tutorials or wisdomjobs or tutorialphp), use below code

Optimizing Regular Expression Queries

  • If the document fields are indexed, query uses indexed values to match the regular expression. This will make the search very fast when compared to the regular expression which scans the whole collection.
  • If the regular expression is a prefix expression, then all the matches are meant to start with a certain string characters. For e.g., if the regex expression is ^tut, then the query will search for only those strings which begin with tut.

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd Protection Status

MongoDB Topics