【发布时间】:2012-12-03 20:49:20
【问题描述】:
我有一个集合,其中包含每个文档的一组字段值。其中之一称为“坐标”。现在,当我在数据库中查询该字段不为空的元素时,它会返回我期望的正确值。
但是我偶尔在 python (Pymongo) 中遇到这个错误:
if not doc['coordinates']
TypeError: 'NoneType' object has no attribute '__getitem__'
这似乎暗示它遇到了一个没有字段“坐标”的记录。我已经创建了包含该字段的文档并且应该存在。
不过我想知道,我该如何处理这个错误并防止这个错误终止我的程序。
这就是我找到适当查询的方式:
cursor = collection.find(
{ "$and" : [
{"term": {"$in": events}},
{ "$or" : [
{"coordinates" : {"$ne": None}},
{"place" : {"$ne" : None}}
]}
]},
{"term" : 1, "coordinates" : 1, "place" : 1, "time_normal" : 1}, tailable = True, timeout = False )
然后我遍历返回的查询,如下:
while cursor.alive:
try:
doc = cursor.next()
CODE IS HERE TO QUERY DB
except StopIteration:
pass
谢谢
【问题讨论】:
标签: python mongodb python-2.7 pymongo