MongoDB/PyMongo: Querying multiple criteria - unex

2019-03-20 10:10发布

问题:

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?

回答1:

You can use $and to join multiple conditions:

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


回答2:

No necessary to use $and, it also works

db.collection.find({"foo":{"$ne":"bar", "$exists":true}})