Reputation: 5025
I'm trying to build mongoDB query based on python's dictionaries. The problem that a key should be unique in dicts. See the example
MongoDB data:
{
"_id" : ObjectId("4dcd3ebc9278000000005158"),
col1 : 'foo'
}
{
"_id" : ObjectId("4dcd3ebc9278000000005159"),
col1 : 'bar'
}
Python code:
dict = {'col1': 'foo'}
dict.update({'col1': 'bar'})
db.test.find(dict)
shows only one line with col1=='bar'
>>> dict
{'col1': 'bar'}
How can I build the right MongoDB query using dictionaries (or anything) which does not need to have unique keys.
Thanks!
Upvotes: 1
Views: 993
Reputation: 366
An alternative method would be to use the $exists
operator in mongodb.
query = {'col1': {'$exists': 'true'}}
db.test.find(dict)
This way you would not have to specify what values col1 could take.
Upvotes: 0
Reputation: 2175
I think the solution for you is just a simple way, you should push each object in a dict and store them in an array:
dict = []
your_obj = {'col1': 'foo'}
dict.append(your_obj)
dict.append({'col1': 'bar'})
for o in dict:
db.test.find(o)
Upvotes: 1
Reputation: 436
Are you looking for documents where 'col1' is either 'foo' OR 'bar'?
If so, then you want db.test.find({'col1': {'$in': ['foo', 'bar']}});
To explain, that query matches documents where the value of col1
is in
the list ['foo', 'bar']
.
Advanced mongodb queries are documented here: http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24in
Upvotes: 3