MongoDB -多个$or操作

bxfogqkk  于 2023-11-17  发布在  Go
关注(0)|答案(4)|浏览(204)

我怎么会有多个$or操作呢?到目前为止,我已经尝试了以下方法,但它会默默地忽略第二个$or。

  1. {
  2. $or: [{a: 2}, {a: 3}],
  3. $or: [{b: 5}, {b: 4}]
  4. }

字符串
我想这是因为我用了两把一模一样的钥匙。有什么办法解决这个问题吗?

f4t66c6m

f4t66c6m1#

Mongo 2.0添加了一个$and运算符,所以你可以这样做一个查询:

  1. db.things.find({$and: [{$or : [{'a':1},{'b':2}]},{$or : [{'a':2},{'b':3}]}] })

字符串
http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24and

v1l68za4

v1l68za42#

JavaScript对象不能有两个同名的属性(你有两个$or),这也会发生在每个不遵守此规则的查询中(只考虑一个属性)。

  1. // try this Javascript code (this will throw an errors some programming languages)
  2. const x = { a: 1, a : 2 };
  3. console.log("x:", x);
  4. // this will output x: {a: 2} // <= the "a: 1" was gone.

字符串
这应该(Nader)应该可以解决你的问题,你也可以把你的查询转换成一个$or,包含所有可能的值,但是它可能会因为更多的值/变量而变得混乱(不推荐,但是它可以摆脱两个同名的属性问题)。

  1. // this will not work (your question)
  2. {
  3. $or: [{a: 2}, {a: 3}],
  4. $or: [{b: 5}, {b: 4}]
  5. }
  6. // this will work (I recommend using $and in your use-case)
  7. {
  8. $or: [
  9. {a: 2, b: 4},
  10. {a: 2, b: 5},
  11. {a: 3, b: 4},
  12. {a: 3, b: 5},
  13. ]
  14. }
  15. // this is a better solution for your problem (Nader).
  16. {
  17. $and: [
  18. { $or: [{a: 2}, {a: 3}] },
  19. { $or: [{b: 5}, {b: 4}] }
  20. }

展开查看全部
xkftehaa

xkftehaa3#

对于多个,比如在sql中,我们使用$in,对于不多个,我们使用$nin vc,这是我们的集合名。我们发现这些字符串包含cpu或memo。

  1. db.collection('vc').find({ "name" : { $in: [ /cpu/, /memo/ ] } }

字符串

pdsfdshx

pdsfdshx4#

$and不会完成这项工作,因为如果第一个失败,第二个$or将不会验证。
从Mongo手册页:

  • $and运算符使用短路求值。如果第一个表达式(例如)的求值结果为false,MongoDB将不会对其余表达式求值。*

嵌套的$or应该可以做到这一点:
{$or:[{$or:['a':1},'b':2}]},{$or:['a':2},'b':3}]})

相关问题