Max Powers
Max Powers

Reputation: 1179

mongodb query in two different arrays

I have been going through the mongodb querying inside an array. I have gotten the example they give to work for me for querying a single array. But how would this work if I had two different arrays and wanted to combine them into a single query? for example item1 and item2 were two different arrays.

# 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 reference doc: https://docs.mongodb.com/manual/reference/operator/query/in/

I should also mention that I am using mongodb to get the idea of what the command would look like, but ultimately this command should work for pymongo as this command will be executed via pymongo.

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

Upvotes: 1

Views: 1326

Answers (1)

Moshe
Moshe

Reputation: 2674

MongoDB "OR" SYNTAX:

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

In your case:

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

Upvotes: 2

Related Questions