使用 $and 和多个 $or 查询 MongoDB
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40388657/
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
Query MongoDB with $and and Multiple $or
提问by juminoz
As stated in the documentation, this is not possible.
正如文档中所述,这是不可能的。
AND Queries With Multiple Expressions Specifying the Same Operator
具有指定相同运算符的多个表达式的 AND 查询
Consider the following example:
考虑以下示例:
db.inventory.find( {
$and : [
{ $or : [ { price : 0.99 }, { price : 1.99 } ] },
{ $or : [ { sale : true }, { qty : { $lt : 20 } } ] }
]
} )
This query will return all select all documents where:
此查询将返回所有选择所有文档,其中:
the price field value equals 0.99 or 1.99, and the sale field value is equal to true or the qty field value is less than 20.
price 字段值等于 0.99 或 1.99,而 sale 字段值等于 true 或 qty 字段值小于 20。
This query cannot be constructed using an implicit AND operation, because it uses the $or operator more than once.
此查询不能使用隐式 AND 运算构造,因为它多次使用 $or 运算符。
What is a workaround to query something like this? This query returns no results on MongoDB 3.2. I have tested the $or blocks separately and they are working fine, but not when they are wrapped in $and block. I assumed I didn't read the documentation incorrectly that this is not supposed to work. The only alternative I have is to push the data to ElasticSearch and query it there instead, but that's also just a workaround.
查询此类内容的解决方法是什么?此查询在 MongoDB 3.2 上不返回任何结果。我已经分别测试了 $or 块并且它们工作正常,但是当它们被包裹在 $and 块中时就不行了。我认为我没有错误地阅读文档,认为这不应该起作用。我唯一的选择是将数据推送到 ElasticSearch 并在那里查询,但这也只是一种解决方法。
{
"$and": [
{
"$or": [
{
"title": {
"$regex": "^.*html .*$",
"$options": "i"
}
},
{
"keywords": {
"$regex": "^.*html .*$",
"$options": "i"
}
}
]
},
{
"$or": [
{
"public": true
},
{
"domain": "cozybid"
}
]
}
]
}
回答by felix
the documentation doesn't say that this is impossible. It only says
文档并没有说这是不可能的。它只说
This query cannot be constructed using an implicit AND operation, because it uses the $or operator more than once.
此查询不能使用隐式 AND 运算构造,因为它多次使用 $or 运算符。
this means that this will work :
这意味着这将起作用:
db.inventory.find( {
$and : [
{ $or : [ { price : 0.99 }, { price : 1.99 } ] },
{ $or : [ { sale : true }, { qty : { $lt : 20 } } ] }
]
} )
but this won't, because it's an implicit$and
with two $or
但这不会,因为它是一个隐含$and
的两个$or
db.inventory.find({
{ $or : [ { price : 0.99 }, { price : 1.99 } ] },
{ $or : [ { sale : true }, { qty : { $lt : 20 } } ] }
})
try it online: mongoplayground.net/p/gL_0gKzGA-u
在线试用:mongoplayground.net/p/gL_0gKzGA-u
Here is a working case with an implicit $and
:
这是一个隐含的工作案例$and
:
db.inventory.find({ price: { $ne: 1.99, $exists: true } })
I guess the problem you're facing is that there is no document matching your request in your collection
我想您面临的问题是您的收藏中没有符合您要求的文件