mongodb学习工作生活MongoDB

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不能省略 示例五

以上配置内容可组合使用

示例:

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/});
结果相同且均为20条

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/} );
三种语句结果相同,均为51条
省略“/”的语句会将元字符中\忽略,需要用\\才能正常使用元字符:
db.getCollection("regex").find({article_authors: { $regex: '\d'} });
结果为280条,且含结果只匹配的字母“d”,含无数字数据
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 });
四种语句结果相同,均为64条
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 });
结果均为7条,第四条与第七条第一行并不是以“This”开头
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”结束,仅无“/”模式下可用*/ 
结果相同,均匹配到“October”

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

db.getCollection("regex2").find({article_title:{$regex:/Reg.*Mission/,$options:'s'}});
db.getCollection("regex2").find({article_title:{$regex:'Reg.*Mission',$options:'s'}});
字段中存在换行符,若无“s”,则结果为空

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

上一篇 下一篇

猜你喜欢

热点阅读