使用 $and 和多个 $or 查询 MongoDB [英] Query MongoDB with $and and Multiple $or

查看:30
本文介绍了使用 $and 和多个 $or 查询 MongoDB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

文档所述,这是不可能的.

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 运算符.

查询此类内容的解决方法是什么?此查询在 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 } } ] }
    ]
} )

但这不会,因为它是带有两个 $or隐式 $and

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆