MongoDB——模糊查询的两种方法
对应mysql的like用法:select * from users where fname like '%zhangsan%';举例:db.users.find({"name":{$regex:/zhangsan/}});模型匹配user集合中name列包含"zhangsan"的数据。{666,888}:表示前面的匹配符出现666~888次;{666}:表示前面的匹配符出现666次;*号:表示前
方法一:类似于结构性数据库的like
db.users.find({fname: /zhangsan/});
对应mysql的like用法:select * from users where fname like '%zhangsan%';
(1)如果要模糊查询以什么开头,方法如下:
db.users.find({fname: /^zhangsan/});
(2)如果要模糊查询以什么结尾,方法如下:
db.users.find({fname: /zhangsan^/});
方法二:正则表达式
常见的正则表达式
.点号:在正则表达式中是一个通配符,它代表所有字符和数字
*号:表示前面的匹配符出现>=0次;
+号:表示前面的匹配符出现>=1次;
?号:表示前面的匹配符出现<=1次;
{666}:表示前面的匹配符出现666次;
{666,888}:表示前面的匹配符出现666~888次;
^:匹配开头;
$:匹配结尾;
(1)模型匹配user集合中name列包含"zhangsan"的数据。
db.users.find({"name":{$regex:/zhangsan/}});
(2)查询某字段开头是"string"的记录,等同于sql的 like ‘string%’
db.mycollection.find({"content.value":{$regex:"^姚明"}})
(3)查询某字段结尾是"string"的记录,等同于sql的 like ‘%string’
db.mycollection.find({"content.value":{$regex:"唱歌$"}})
(4)查询某字段结尾是"string"的记录,等同于sql的 like ‘%string’
db.mycollection.find({"content.value":{$regex:"唱歌$"}})
(5)查询某字段不是"string"打头的记录,等同于sql的not like ‘%string’
db.mycollection.find({"content.value":{$regex:"[^唱歌]"}})
更多推荐
所有评论(0)