MongoDB如何执行like模糊查询?
MongoDB执行like查询的方法
创建几条数据
db.users.insert({name: 'paulo'})
db.users.insert({name: 'patric'})
db.users.insert({name: 'pedro'})查询包含字母a的结果,等同于 like '%a%'
db.users.find({name: /a/})  //like '%a%'查询结果为: paulo, patric
查询开头字母是pa的结果,等同于 like 'pa%'
db.users.find({name: /^pa/}) //like 'pa%' 查询结果为: paulo, patric
查询结尾字母是ro的结果,等同于 like '%ro'
db.users.find({name: /ro$/}) //like '%ro'查询结果为: pedro
此外,MongoDB查询条件可以使用正则表达式,模糊查询可以使用$regex操作符或直接使用正则表达式对象。官方链接
| MySQL | MongoDB | 
|---|---|
| select * from student where name like '%joe%' | db.student.find({name:{$regex:/joe/}}) | 
| select * from student where name regexp 'joe' | db.student.find({name:/joe/}) |