Query MongoDB with $and and Multiple $or

前端 未结 1 1505
旧巷少年郎
旧巷少年郎 2020-12-16 02:51

As stated in the documentation, this is not possible.


AND Queries With Multiple Expressions Specifying the Same Operator

Consider the following exampl

相关标签:
1条回答
  • 2020-12-16 03:25

    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.

    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

    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

    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

    0 讨论(0)
提交回复
热议问题