1

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!

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.