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 of MongoDB Regular Expression

{ 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' collection.

{ "_id" : ObjectId("5b7ddc4f529cbc23546dc4c7"), "name" : "Jorz Rai", "age" : 10, "class" : "5A" }
{ "_id" : ObjectId("5b7ddf10529cbc23546dc4c8"), "name" : "Rana Soi", "age" : 11, "class" : "5C" }
{ "_id" : ObjectId("5b7de0f4529cbc23546dc4c9"), "name" : "Andy Joya", "age" : 11, "class" : "5C" }
{ "_id" : ObjectId("5b7de0f4529cbc23546dc4ca"), "name" : "Mary Soi", "age" : 11, "class" : "5C" }
{ "_id" : ObjectId("5b7de0f4529cbc23546dc4cb"), "name" : "Priska Somya", "age" : 12, "class" : "6A" }

The following query returns all the students name containg 'an'.

db.students.find( { name: { $regex: /an/i } } )
Output of the above code -
{ "_id" : ObjectId("5b7ddf10529cbc23546dc4c8"), "name" : "Rana Soi", "age" : 11, "class" : "5C" }
{ "_id" : ObjectId("5b7de0f4529cbc23546dc4c9"), "name" : "Andy Joya", "age" : 11, "class" : "5C" }
mongodb regular expression





Read more articles


General Knowledge



Learn Popular Language