使用$和和$ $或查询MongoDB

jum*_*noz 5 search expression operators mongodb

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


和多个表达式的查询指定相同的运算符

请考虑以下示例:

db.inventory.find( {
    $and : [
        { $or : [ { price : 0.99 }, { price : 1.99 } ] },
        { $or : [ { sale : true }, { qty : { $lt : 20 } } ] }
    ]
} )
Run Code Online (Sandbox Code Playgroud)

此查询将返回所有选择所有文档,其中:

price字段值等于0.99或1.99,sale字段值等于true或qty字段值小于20.

无法使用隐式AND操作构造此查询,因为它多次使用$或运算符.


查询此类内容的解决方法是什么?此查询在MongoDB 3.2上不返回任何结果.我已经分别测试了$或块,它们工作正常,但不是当它们被包裹在$和块中时.我假设我没有错误地阅读文档,认为这不应该工作.我唯一的选择是将数据推送到ElasticSearch并在那里查询,但这也只是一种解决方法.

{
    "$and": [
        {
            "$or": [
                {
                    "title": {
                        "$regex": "^.*html .*$",
                        "$options": "i"
                    }
                },
                {
                    "keywords": {
                        "$regex": "^.*html .*$",
                        "$options": "i"
                    }
                }
            ]
        },
        {
            "$or": [
                {
                    "public": true
                },
                {
                    "domain": "cozybid"
                }
            ]
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

fel*_*lix 11

文档并没有说这是不可能的.它只说

无法使用隐式AND操作构造此查询,因为它多次使用$或运算符.

这意味着这将有效:

db.inventory.find( {
    $and : [
        { $or : [ { price : 0.99 }, { price : 1.99 } ] },
        { $or : [ { sale : true }, { qty : { $lt : 20 } } ] }
    ]
} )
Run Code Online (Sandbox Code Playgroud)

但这不会(隐含$和)

db.inventory.find({
        { $or : [ { price : 0.99 }, { price : 1.99 } ] },
        { $or : [ { sale : true }, { qty : { $lt : 20 } } ] }
})
Run Code Online (Sandbox Code Playgroud)

这会工作(隐含的$和)

db.inventory.find({ price: { $ne: 1.99, $exists: true } })
Run Code Online (Sandbox Code Playgroud)

我想您面临的问题是您的收藏中没有与您的请求相匹配的文档