MongoDB 正则查询 $regex
2019-07-22 本文已影响37人
沧海2122537190
$regex基本语法#
{ <field>: { $regex: /pattern/, $options: '<options>' } }
{ <field>: { $regex: 'pattern', $options: '<options>' } }
{ <field>: { $regex: /pattern/<options> } }
{ <field>: /pattern/<options> }//省略regex
pattern为正则表达式
options为配置选项
Option | 介绍 | 限制 | 示例 |
---|---|---|---|
i |
忽略大小写情况 | 无 | 示例二 |
m |
多行匹配模式,当有锚点^和$,且文档为多行时,分行进行开头结尾匹配,而不是对字符串开头结尾进行匹配。 | 无 | 示例三 |
x |
忽略非转义的空白字符 |
$regex 和$options 不能省略 |
示例四 |
s |
点号(.)元字符会匹配所有字符,包括换行符(\n) |
$regex 和$options 不能省略 |
示例五 |
以上配置内容可组合使用
示例:
- 一、无配置选项
1.查找article_abstract_en字段中,含“literature”的数据
db.getCollection("regex").find({article_abstract_en: { $regex: /literature/}});
db.getCollection("regex").find({article_abstract_en: { $regex: 'literature'}});
db.getCollection("regex").find({article_abstract_en: /literature/});

2.查找article_authors字段中,含数字的数据
db.getCollection("regex").find({article_authors: { $regex: '\\d'} });
db.getCollection("regex").find({article_authors: { $regex: /\d/} });
db.getCollection("regex").find({article_authors: /\d/} );

省略“/”的语句会将元字符中
\
忽略,需要用\\
才能正常使用元字符:
db.getCollection("regex").find({article_authors: { $regex: '\d'} });

- 二、配置“i”应用:忽略大小写
1.查找article_abstract_en中含“Some”的数据
未忽略大小写时查询结果
结果共7条
db.getCollection("regex").find({article_abstract_en:{$regex:/Some/,$options:'i'}});
db.getCollection("regex").find({article_abstract_en:{$regex:'Some',$options:'i'}});
db.getCollection("regex").find({article_abstract_en:{$regex:/Some/i}});
db.getCollection("regex").find({article_abstract_en:/Some/i });

- 三、配置“m”应用:多行匹配
1.查找article_abstract_en中,以This开头的数据
无m时查询结果:
结果共5条
db.getCollection("regex2").find({article_abstract_en:{$regex:/^This/,$options:'m'}});
db.getCollection("regex2").find({article_abstract_en:{$regex:'^This',$options:'m'}});
db.getCollection("regex2").find({article_abstract_en:{$regex:/^This/m}});
db.getCollection("regex2").find({article_abstract_en:/^This/m });

- 四、配置“x”应用
db.getCollection("regex2").find({article_title:{$regex:/O ct/,$options:'x'}});
db.getCollection("regex2").find({article_title:{$regex:'O #month\n ct#month\n',$options:'x'}});
/*其中 "#month\n"为字符串中的注释,以“#”开始,“\n”结束,仅无“/”模式下可用*/

$regex
和$options
都不可省略,否则会有以下报错
[Error] SyntaxError: invalid regular expression flag x
- 五、配置“s”应用
db.getCollection("regex2").find({article_title:{$regex:/Reg.*Mission/,$options:'s'}});
db.getCollection("regex2").find({article_title:{$regex:'Reg.*Mission',$options:'s'}});

$regex
和$options
都不可省略,否则会有以下报错
[Error] SyntaxError: invalid regular expression flag s