MongoDB 查询:字段不存在或具有特定值
我想查询 mongo 集合中的记录,这些记录要么没有名为“scheme”的字段的值,要么明确具有“scheme”的值“http”。听起来很简单,但事实证明这个问题比最初看起来更复杂。
由于 db.collection.find({'scheme': None}) 返回“scheme”未定义(无索引字段)的所有记录,我最初假设以下内容可行:
db.collection.find({'scheme': {'$in': ['http', None]}})
但是,这似乎排除“scheme”未定义的值,因此我只能假设它正在搜索 schema 为“http”或明确定义为“None”的记录。这似乎有点违反直觉,但我们已经做到了。我的第二次尝试如下:
db.collection.find( {'$or': [{'scheme': {'$exists': False}}, {'scheme': 'http'}]})
这也排除了方案未定义的结果。这一次,我什至想不出失败的逻辑原因。
任何想法为什么会失败,以及如何让它按预期工作?
谢谢
编辑:只是想我注意到我正在通过Python(pymongo)执行此查询,这解释了None
(通过Javascript的null
)
I'd like to query a mongo collection for records which either don't have a value for a field named 'scheme', or explicitly have the value 'http' for 'scheme'. Sounds pretty easy, but this problem has proved more complex than it first appears.
Since db.collection.find({'scheme': None})
returns all records where 'scheme' is undefined (no index field), I initially assumed the following would work:
db.collection.find({'scheme': {'$in': ['http', None]}})
However, this seems to exclude values in which 'scheme' is undefined, so I can only assume it is searching for records where scheme is either 'http', or explicitly defined to be None
. This seems to be a bit counterintuitive, but there we have it. My second attempt was the following:
db.collection.find( {'$or': [{'scheme': {'$exists': False}}, {'scheme': 'http'}]})
This also excludes result where scheme is undefined. This time, I can't even think of a logical reason why this is failing.
Any ideas why this is failing, and how I can get it to work as desired?
Thanks
EDIT: Just thought I'd note that I'm performing this query through Python (pymongo), which explains the None
(over Javascript's null
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
已解决:这显然是我的 mongodb 版本(1.4.4)的问题,该问题已在 1.6.5 中解决。
Resolved: This is apparently an issue of my version of mongodb (1.4.4), the issue is solved in 1.6.5.