MongoDB $ 或查询
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14534984/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MongoDB $or query
提问by Fruitful
I run following query in mongo shell:
我在 mongo shell 中运行以下查询:
db.Profiles.find ( { $or : [ { "name" : "gary" }, {"name":"rob} ] } )
It just returns nothing as expected(JSON)?
它只是按预期返回任何内容(JSON)?
回答by AD7six
Use $in
使用 $in
For the query in the question, it's more appropriate to use $in
对于问题中的查询,使用$in更合适
db.Profiles.find ( { "name" : { $in: ["gary", "rob"] } } );
Why doesn't it work
为什么它不起作用
There's a missing quote - the cli is waiting for you to finish the second part of your or:
缺少引用 - cli 正在等待您完成您的或的第二部分:
db.Profiles.find ( { $or : [ { "name" : "gary" }, {"name":"rob} ] } )
..............................................................^
You need to finish the query sufficiently for the cli to parse it for it to then say there's a syntax error.
您需要足够地完成查询,以便 cli 对其进行解析,然后说存在语法错误。
Case insensitive matching
不区分大小写匹配
As indicated by a comment, if you want to search in a case insensitive manner, then you either use $or
with a $regex:
正如评论所指出的,如果你想在不区分大小写的方式进行搜索,那么你要么使用$or
一个$正则表达式:
db.Profiles.find ( { $or : [ { "name" : /^gary/i }, {"name": /^rob/i } ] } )
Or, you simply use one regex:
或者,您只需使用一个正则表达式:
db.Profiles.find ( { "name" : /^(gary|rob)/i } )
However, a regex query that doesn't start with a fixed string cannot use an index (it cannot use an index and effectively do "start here until no match found then bail") and therefore is sub-optimal. If this is your requirement, it's a better idea to store a normalized name field (e.g. name_lc
- lower case name) and query on that:
但是,不以固定字符串开头的正则表达式查询不能使用索引(它不能使用索引并有效地执行“从这里开始直到没有找到匹配然后保释”),因此是次优的。如果这是您的要求,最好存储规范化的名称字段(例如name_lc
- 小写名称)并对其进行查询:
db.Profiles.find ( { "name_lc" : { $in: ["gary", "rob"] } } );