我想用SQL查询一些东西,比如查询:
SELECT * FROM users WHERE name LIKE '%m%'
如何在MongoDB中实现这一点?我在文档中找不到这样的操作员。
我想用SQL查询一些东西,比如查询:
SELECT * FROM users WHERE name LIKE '%m%'
如何在MongoDB中实现这一点?我在文档中找不到这样的操作员。
当前回答
还可以按如下方式使用通配符过滤器:
{"query": { "wildcard": {"lookup_field":"search_string*"}}}
请务必使用*。
其他回答
FullName类似于“last”,两个日期之间的状态==“结束”:
db.orders.find({
createdAt:{$gt:ISODate("2017-04-25T10:08:16.111Z"),
$lt:ISODate("2017-05-05T10:08:16.111Z")},
status:"Pending",
fullName:/last/}).pretty();
status==“待定”,orderId LIKE“PHA871674”:
db.orders.find({
status:"Pending",
orderId:/PHA876174/
}).pretty();
db.users.insert({name: 'patrick'})
db.users.insert({name: 'petra'})
db.users.insert({name: 'pedro'})
因此:
For:
db.users.find({name: /a/}) // Like '%a%'
输出:patrick,petra
For:
db.users.find({name: /^pa/}) // Like 'pa%'
输出:patrick
For:
db.users.find({name: /ro$/}) // Like '%ro'
输出:pedro
在SQL中,“like”查询如下所示:
select * from users where name like '%m%'
在MongoDB控制台中,如下所示:
db.users.find({"name": /m/}) // Not JSON formatted
db.users.find({"name": /m/}).pretty() // JSON formatted
此外,pretty()方法将在所有地方生成一个格式化的JSON结构,这样可读性更强。
下面是使用正则表达式进行字符串搜索的不同类型的要求和解决方案。
您可以使用包含单词的正则表达式,例如like。也可以使用$options=>i进行不区分大小写的搜索。
包含字符串
db.collection.find({name:{'$regex' : 'string', '$options' : 'i'}})
不包含字符串,仅包含正则表达式
db.collection.find({name:{'$regex' : '^((?!string).)*$', '$options' : 'i'}})
完全不区分大小写的字符串
db.collection.find({name:{'$regex' : '^string$', '$options' : 'i'}})
以字符串开头
db.collection.find({name:{'$regex' : '^string', '$options' : 'i'}})
以字符串结尾
db.collection.find({name:{'$regex' : 'string$', '$options' : 'i'}})
将正则表达式备忘表作为书签,并作为您可能需要的任何其他更改的参考。
您可以使用MongoDB 2.6的新功能:
db.foo.insert({desc: "This is a string with text"});
db.foo.insert({desc:"This is a another string with Text"});
db.foo.ensureIndex({"desc":"text"});
db.foo.find({
$text:{
$search:"text"
}
});