MongoDB/PyMongo:查询多个条件-意外结果 [英] MongoDB/PyMongo: Querying multiple criteria - unexpected results

查看:1451
本文介绍了MongoDB/PyMongo:查询多个条件-意外结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个集合,其中某些对象具有键foo.现在,我尝试查询确实具有此键但没有特定值bar的所有对象.为此,我使用以下查询:

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

我认为这两个条件都是通过逻辑AND连接的.但是,我也得到了不具有键foo的对象.实际上,当我只使用查询时,会得到相同的结果

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

我正确地只获得了带有foo的对象,但是显然它们都是如此,所以其中一些具有值bar.

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?

推荐答案

您可以使用$and来加入多个条件:

You can use $and to join multiple conditions:

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

这篇关于MongoDB/PyMongo:查询多个条件-意外结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆