$regex¶
On this page
-
$regex¶ The
$regexoperator provides regular expression capabilities for pattern matching strings in queries. MongoDB uses Perl compatible regular expressions (i.e. “PCRE.”)You can specify regular expressions using regular expression objects (i.e.
/pattern/) or using the$regexoperator. The following examples are equivalent:These expressions match all documents in
collectionwhere the value offieldmatches the case-insensitive regular expressionacme.*corp.-
$options¶ $regexprovides four option flags:itoggles case insensitivity, and allows all letters in the pattern to match upper and lower cases.mtoggles multiline regular expression. Without this option, all regular expression match within one line.If there are no newline characters (e.g.
\n) or no start/end of line construct, themoption has no effect.xtoggles an “extended” capability. When set,$regexignores all white space characters unless escaped or included in a character class.Additionally, it ignores characters between an un-escaped
#character and the next new line, so that you may include comments in complicated patterns. This only applies to data characters; white space characters may never appear within special character sequences in a pattern.The
xoption does not affect the handling of the VT character (i.e. code 11.)
New in version 1.9.0.
sallows the dot (e.g..) character to match all characters including newline characters.
Only the
iandmoptions are available for the native JavaScript regular expression objects (e.g./acme.*corp/i). To usexandsoptions, you must use the$regexoperator with the$optionssyntax.
To combine a regular expression match with other operators, you need to use the
$regexoperator. For example:This expression returns all instances of
fieldincollectionthat match the case insensitive regular expressionacme.*corpthat don’t matchacmeblahcorp.-
Behavior¶
PCRE Matching Engine¶
$regex uses “Perl Compatible Regular Expressions” (PCRE) as
the matching engine.
$in Expressions¶
To include a regular expression in an $in query expression, you can
only use JavaScript regular expression objects (i.e. /pattern/ ).
You cannot use $regex operator expressions inside an
$in.
Index Use¶
$regex can only use an index efficiently
when the regular expression has an anchor for the beginning (i.e. ^)
of a string and is a case-sensitive match. Additionally, while
/^a/, /^a.*/, and /^a.*$/ match equivalent strings, they
have different performance characteristics. All of these expressions
use an index if an appropriate index exists; however, /^a.*/,
and /^a.*$/ are slower. /^a/ can stop scanning after matching
the prefix.