MongoDB/PyMongo: Querying multiple criteria - unexpected results

Christian picture Christian · May 10, 2014 · Viewed 19.3k times · Source

I have a collection where some of the objects feature an key foo. I now try to query for all objects that indeed have this key but not with the specific value bar. For this I use the following query:

collection.find({'foo': {'$exists': True}, 'foo': {'$ne': 'bar'}})

I thought that both criteria are connected via a logical AND. However, I get also objects that don't feature key foo. In fact, I get the same result when I just use the query

collection.find({'foo': {'$ne': 'bar'}})

On the other hans, if I use

collection.find({'foo': {'$exists': True}})

I correctly only get objects with foo but obvisouly all of them, so some of them have the value bar.

How do I have to formulate my query to achieve my initial result? Is there a kind of order in which multiple criteria are tested? Do I explicitly specify the logical AND of both criteria?

Answer

alecxe picture alecxe · May 10, 2014

You can use $and to join multiple conditions:

collection.find({"$and": [{"foo": {'$ne': 'bar'}}, 
                          {"foo": {'$exists': True}}]})