我有一个集合,每个文档都有一组字段值。其中之一称为“坐标”。现在,当我在数据库中查询该字段不为空的元素时,它会返回我期望的正确值。
但是我不时在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
谢谢