MongoDB $或查询 [英] MongoDB $or query
问题描述
我在mongo shell中运行以下查询:
I run following query in mongo shell:
db.Profiles.find ( { $or: [ {"name": "gary"}, {"name": "rob"} ] } )
它只是不返回预期的(JSON)吗?
It just returns nothing as expected(JSON)?
推荐答案
使用$ in
对于问题中的查询,更适合使用 $ in >
db.Profiles.find ( { "name" : { $in: ["gary", "rob"] } } );
为什么不起作用
缺少引号-cli正在等待您完成或"的第二部分:
Why doesn't it work
There's a missing quote - the cli is waiting for you to finish the second part of your or:
db.Profiles.find ( { $or : [ { "name" : "gary" }, {"name":"rob} ] } )
..............................................................^
您需要充分完成查询,以便cli对其进行解析,然后再说出语法错误.
You need to finish the query sufficiently for the cli to parse it for it to then say there's a syntax error.
如注释所示,如果要以不区分大小写的方式进行搜索,则可以将$or
与
As indicated by a comment, if you want to search in a case insensitive manner, then you either use $or
with a $regex:
db.Profiles.find ( { $or : [ { "name" : /^gary/i }, {"name": /^rob/i } ] } )
或者,您只需使用一个正则表达式:
Or, you simply use one regex:
db.Profiles.find ( { "name" : /^(gary|rob)/i } )
但是,不是以固定字符串开头的正则表达式查询不能使用索引(它不能使用索引,并且实际上会执行从此处开始,直到找不到匹配项然后保释"),因此是次优的.如果这是您的要求,则最好存储一个规范化的名称字段(例如name_lc
-小写名称)并在该字段上进行查询:
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:
db.Profiles.find ( { "name_lc" : { $in: ["gary", "rob"] } } );
这篇关于MongoDB $或查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!