MongoDB $or query

纵饮孤独 提交于 2019-11-26 09:53:32

问题


I run following query in mongo shell:

db.Profiles.find ( { $or: [ {\"name\": \"gary\"}, {\"name\": \"rob\"} ] } )

It just returns nothing as expected(JSON)?


回答1:


Use $in

For the query in the question, it's more appropriate to use $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:

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.

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:

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:

db.Profiles.find ( { "name_lc" : { $in: ["gary", "rob"] } } );


来源:https://stackoverflow.com/questions/14534984/mongodb-or-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!