mongodb使用AND和OR进行查询 [英] mongodb queries both with AND and OR
问题描述
我可以在mongodb查询中使用OR和AND的组合吗?
can I use combination of OR and AND in mongodb queries?
下面的代码无法正常工作
the code below doesn't work as expected
db.things.find({
$and:[
{$or:[
{"first_name" : "john"},
{"last_name" : "john"}
]},
{"phone": "12345678"}
]});
数据库内容:
> db.things.find();
{ "_id" : ObjectId("4fe8734ac27bc8be56947d60"), "first_name" : "john", "last_name" : "hersh", "phone" : "2222" }
{ "_id" : ObjectId("4fe8736dc27bc8be56947d61"), "first_name" : "john", "last_name" : "hersh", "phone" : "12345678" }
{ "_id" : ObjectId("4fe8737ec27bc8be56947d62"), "first_name" : "elton", "last_name" : "john", "phone" : "12345678" }
{ "_id" : ObjectId("4fe8738ac27bc8be56947d63"), "first_name" : "eltonush", "last_name" : "john", "phone" : "5555" }
查询以上查询时-我什么也没得到!
when querying the above query - i get nothing!
> db.things.find({$and:[{$or:[{"first_name" : "john"}, {"last_name" : "john"}]},{"phone": "12345678"}]});
>
我正在使用mongo 1.8.3
I'm using mongo 1.8.3
推荐答案
我相信$ and仅在MongoDB v2.0 +中受支持.我很惊讶控制台首先接受了该表达式.我将尝试针对我拥有的1.8服务器进行重新创建.
I believe $and is only supported in MongoDB v2.0+. I'm surprised that the console accepted the expression in the first place. I'll try to recreate against a 1.8 server I have.
还请检查
Also check 10Gen's Advanced Query Documentation for $and
.
更新
我将您的样本数据输入到v1.8x和v2.0x MongoDB服务器中.该查询在v2.0x上有效,而在v1.8x上失败.这证实了我(和Miikka的)怀疑,原因是$and
和您的服务器版本有关.
I entered your sample data into both a v1.8x and v2.0x MongoDB server. The query works on the v2.0x and fails on the v1.8x. This confirms my (and Miikka's) suspicions that the problem is with $and
and your server version.
我在网上这里找到了一个(可能)聪明的解决方法.我希望这会有所帮助.
I found a (arguably) clever workaround for this on the Web here. I hope this helps.
-SethO
这篇关于mongodb使用AND和OR进行查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!