MongoDB/PyMongo: Querying multiple criteria - unexpected results

谁说我不能喝 提交于 2019-11-29 14:29:25

问题


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}})


来源:https://stackoverflow.com/questions/23577172/mongodb-pymongo-querying-multiple-criteria-unexpected-results

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!