mongodb查询两个不同的数组

时间:2017-06-15 17:35:16

标签: arrays mongodb pymongo

我一直在查询阵列中的mongodb查询。我得到了他们为我工作查询单个数组的例子。但是,如果我有两个不同的数组并希望将它们组合成一个查询,那么它将如何工作?例如,item1和item2是两个不同的数组。

# example given in mongodb document
db.inventory.find( { qty: { $in: [ 5, 15 ] } } )

# example of query of what I am trying achieve query two arrays 
db.inventory.find( { item1: { $in: [ item1_value ] } { item2: { $in: [ item2_value ] } } )

mongodb参考文档:https://docs.mongodb.com/manual/reference/operator/query/in/

我还应该提一下,我正在使用mongodb来了解命令的外观,但最终这个命令应该适用于pymongo,因为这个命令将通过pymongo执行。

# correct query example as given by Moshe
db.inventory.find({ 
      $or: [ 
             { item1: { $in: [ item1_value ] }}, 
             { item2: { $in: [ item2_value ] }}
       ]
});

1 个答案:

答案 0 :(得分:1)

MongoDB" OR"语法:

{ $or: [ { <expression1> }, { <expression2> }, ... , { <expressionN> } ] }

在你的情况下:

db.inventory.find({ 
      $or: [ 
             { item1: { $in: [ item1_value ] }, 
             { item2: { $in: [ item2_value ] }
       ]
});