简体   繁体   English

MongoDB $or 运算符分别用于多个字段

[英]MongoDB $or operator for multiple fields separately

Looks like MongoDB supports $or operator only in the query root, and not per field query.看起来 MongoDB 仅在查询根中支持 $or 运算符,而不是每个字段查询。 So this doesn't work:所以这不起作用:

db.collection.find({
    foo: {
        $or: [ fooQuery1, fooQuery2 ]
    },
    bar: {
        $or: [ barQuery1, barQuery2 ]
    }
})

so we have to write it like:所以我们必须这样写:

db.collection.find({
    $or: [
        { foo: fooQuery1, bar: barQuery1 },
        { foo: fooQuery1, bar: barQuery2 },
        { foo: fooQuery2, bar: barQuery1 },
        { foo: fooQuery1, bar: barQuery2 },
    ]
})

Basically write all possible combinations for foo and bar .基本上为foobar编写所有可能的组合。 But this is insane when we have to query by >2 fields with >2 OR-statements each.但是当我们必须通过 >2 个字段和每个 >2 个 OR 语句进行查询时,这很疯狂。

It is quite easy to write a function which takes the fields and its OR statements from the first example and to generate all possible variations from the second example.编写一个函数,从第一个示例中获取字段及其 OR 语句,并从第二个示例中生成所有可能的变体,这是非常容易的。 But is there some MongoDB native approach, may be we are missing here something.但是是否有一些 MongoDB 本机方法,可能是我们在这里遗漏了一些东西。

And may be you know the reason, why the first approach is not supported?也许您知道原因,为什么不支持第一种方法? So that we better understand mongodb internals.以便我们更好地了解 mongodb 内部结构。

Thank you.谢谢你。

There are a couple of ways this query could be written, but it depends on the actual operations contained in each query.可以通过多种方式编写此查询,但这取决于每个查询中包含的实际操作。

If the queries are checking equality or a regular expression, you could use the $in operator, like如果查询正在检查相等性或正则表达式,则可以使用$in运算符,例如

{
   foo: { $in: [ "fooValue1", /^fooPrefix/ ]},
   bar: { $in: [ "barValue1", "barValue2" ]}
}

If the subqueries have other tests, like inequality or existence, you could combine each field's queries in a separate $or , with an $and operator to ensure a match from each one, like:如果子查询有其他测试,例如不等式或存在性,您可以将每个字段的查询组合在一个单独的$or ,并使用$and运算符来确保每个字段的匹配,例如:

{$and: [
   {$or: [{foo: fooQuery1}, {foo: fooQuery2}]},
   {$or: [{bar: barQuery1}, {bar: barQuery2}]}
]}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM