使用$ and和多个$ or查询MongoDB [英] Query MongoDB with $and and Multiple $or
问题描述
文档中所述,这是不可能的.
As stated in the documentation, this is not possible.
请考虑以下示例:
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:
价格字段值等于0.99或1.99,并且 sale字段值等于true或qty字段值小于20.
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.
不能使用隐式AND运算来构造此查询,因为它多次使用$ or运算符.
This query cannot be constructed using an implicit AND operation, because it uses the $or operator more than once.
查询这样的东西有什么解决方法?该查询在MongoDB 3.2上不返回任何结果.我已经分别测试了$ or块,并且它们工作正常,但是当它们包装在$ and块中时,还不能正常工作.我以为我没有错误地阅读文档,所以这是行不通的.我唯一的选择是将数据推送到ElasticSearch并在那里查询,但这只是一种解决方法.
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.
{
"$and": [
{
"$or": [
{
"title": {
"$regex": "^.*html .*$",
"$options": "i"
}
},
{
"keywords": {
"$regex": "^.*html .*$",
"$options": "i"
}
}
]
},
{
"$or": [
{
"public": true
},
{
"domain": "cozybid"
}
]
}
]
}
推荐答案
文档没有说这是不可能的.它只说
the documentation doesn't say that this is impossible. It only says
不能使用隐式AND运算来构造此查询, 因为它多次使用$ or运算符.
This query cannot be constructed using an implicit AND operation, because it uses the $or operator more than once.
这意味着它将起作用:
db.inventory.find( {
$and : [
{ $or : [ { price : 0.99 }, { price : 1.99 } ] },
{ $or : [ { sale : true }, { qty : { $lt : 20 } } ] }
]
} )
但这不会,因为它是隐式 $and
,其中有两个 $or
but this won't, because it's an implicit $and
with two $or
db.inventory.find({
{ $or : [ { price : 0.99 }, { price : 1.99 } ] },
{ $or : [ { sale : true }, { qty : { $lt : 20 } } ] }
})
在线试用: mongoplayground.net/p/gL_0gKzGA-u
这是一个带有隐式 $and
的工作案例:
Here is a working case with an implicit $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
这篇关于使用$ and和多个$ or查询MongoDB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!