使用 update_many 方法禁止创建新字段

Disable the creation of new fields with update_many method

我正在使用 PyMongo 驱动程序,但 update_many 方法有问题。

如果我尝试更新文档中不存在的字段的值,则会创建该字段。我希望该方法引发错误。

因为我正在开发自己的库,所以我可以编写专门解决这个问题的代码。因此,我对您可以提供给我的所有解决方案都很感兴趣。

您想要的是仅更新包含给定字段的文档。

为此,您需要在过滤条件中使用 $exists 查询运算符 select 仅那些文档。

db.collection.update_many({'fiedname': {'$exists': True}}, update_document)

如果您想在没有文档符合您的查询条件时引发异常,最好的方法是在查询后检查 modified_count or matched_count 的值。如果它等于 0,那么您将引发异常。

一切都放在一起:

update_result = db.collection.update_many({'fiedname': {'$exists': True}}, update_document)
if update_result.modified_count == 0: # you can also use matched_count
    # raise your exception or what do whatever you want here.