pythonic方法检查MongoDB文档中的字段是否存在于条件上



我读过的所有答案显示要使用以下代码来找出集合中的字段是否存在。:

db.inventory.find( { qty: { $exists: true, $ne: false } } )

我正在寻找在当前检查的当前文档中有条件检查的东西,上面有某些字段/键。当然,我尝试做类似:

的事情
doc['properties.color'] is None:
     print("Property does not exists")

但是我的文件使它变得更加困难。并非我所有的文档都在字段中具有该属性,因此导致错误:

KeyError: u'properties.color'

这就是为什么我在每个文档循环时都需要条件语句的原因。我希望有人可以提供帮助。

谢谢。

一般意见是,pythonic方法是寻求宽恕而不是许可。

假设您发布的代码段是在这样的上下文中:

if doc['properties.color'] is None:
    print("Property does not exists")
else:
    # do something with doc['properties.color'], e.g.:
    color = doc['properties.color']

如果您要求宽恕而不是允许,则应使用所面临的错误而不是反对:

try:
    # do something with doc['properties.color'], e.g.:
    color = doc['properties.color']
except KeyError:
    # this would be your `if`-branch from above
    # handle this case:
    print("Property does not exist")

使用pymongo您可以像检查字典一样检查。例如:

document = collection.find_one({"author_id": author_id})
if "author_username" in document:
    print("Author has a username)

最新更新