MongoDB Regular Expression

Regular Expression is useful for flexible string matching. It provides patterns or a sequence of characters for matching text and define search pattern. Mongodb provides $regex operator for pattern matching. It uses the Perl Compatible Regular Expression (PCRE) library to match regular expressions. The regular expression syntax allowed by PCRE is also allowed in MongoDB.

Syntax

 
{ field: { $regex: /pattern/, $options: 'options' } }
 

The following options are available for use in regular expression.

Option Description
i used for case insensitivity to match uppercase and lowercase.
m use to pattern match at the beginning (^) or end of each line ($) for strings with multiline values.
x used to ignore all white space characters in the $regex pattern.

Suppose we have the following students data.

mongodb

and we need to get all students name containg 'an'.

db.students.find( { name: { $regex: /an/i } } )
mongodb regular expression