发布于 2015-09-14 15:08:34 | 238 次阅读 | 评论: 0 | 来源: 网络整理

$regex

The $regex operator 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 or using the $regex operator. The following examples are equivalent:

db.collection.find( { field: /acme.*corp/i } );
db.collection.find( { field: { $regex: 'acme.*corp', $options: 'i' } } );

These expressions match all documents in collection where the value of field matches the case-insensitive regular expression acme.*corp.

$regex uses “Perl Compatible Regular Expressions” (PCRE) as the matching engine.

$options

$regex provides four option flags:

  • i toggles case insensitivity, and allows all letters in the pattern to match upper and lower cases.

  • m toggles 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, the m option has no effect.

  • x toggles an “extended” capability. When set, $regex ignores 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 x option does not affect the handling of the VT character (i.e. code 11.)

1.9.0 新版功能.

  • s allows the dot (e.g. .) character to match all characters including newline characters.

$regex only provides the i and m options for the native JavaScript regular expression objects (e.g. /acme.*corp/i). To use x and s you must use the “$regex” operator with the “$options” syntax.

To combine a regular expression match with other operators, you need to use the “$regex” operator. For example:

db.collection.find( { field: { $regex: /acme.*corp/i, $nin: [ 'acmeblahcorp' ] } );

This expression returns all instances of field in collection that match the case insensitive regular expression acme.*corp that don’t match acmeblahcorp.

$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.

最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务