Reputation: 1417
My MongoDB documents look like:
{
'x': 1,
'y': 2,
'z': 3
},
{
'x': 10,
'y': 20,
'z': 30
},
{
'x': 100,
'y': 200,
'z': 300
},
and the queries look like:
query_1 = {
'x': [1, 100]
}
query_2 = {
'x': [10],
'z': [2]
}
Unfortunately, when we do collection.find(query_1)
or collection.find(query_2)
, we get no results which is because of the lists in the queries. How can I make Mongo take my queries? Please note that the 'values' of my query dictionaries are always lists.
EDIT:
Expanding on Belly Buster's answer below, I believe if I do:
{
'$or': [
{'x': {'$in': ['item1', 'item2']}},
{'y': {'$in': ['item1', 'item2']}}
]
}
answers my question. However, I feel that there is a better way to achieve this. Is there?
Upvotes: 1
Views: 963
Reputation: 8814
Query 1 you are searching on a field x
that contains a list [1, 100]
. As there aren't any records matching, you get no results. Now if you wanted to search x
for either 1 or 100, you need to use the $in
operator; your query should be:
result = db.mycollection.find({'x': {'$in': [1, 100]}})
Query 2 you are searching on a field x
containing a list [10]
and a field z
containing a list [2]
. Again there's nothing matching that in your data.
I'm not sure what query you are trying to perform for this, but if it is x == 10 or z == 2
, then your query is :
result = db.mycollection.find({'$or': [{'x': 10}, {'z': 2}]})
Upvotes: 1