【问题标题】:How to update a field in a Firestore document only if it exists (using Python)?仅当 Firestore 文档中的字段存在时(使用 Python),如何更新该字段?
【发布时间】:2021-04-20 23:20:24
【问题描述】:
Firestore documentation 解释说您可以使用doc_ref.update({'key': 'value'}) 来更新文档中的单个字段(如果该字段不存在则创建它)。
问题是:在我的用例中,我如果该字段不存在,我不想创建它(宁愿跳过)。另外,如果我确实需要创建它,doc_ref.set({'key': 'value'}, merge=True) 会提供我想要的。
【问题讨论】:
标签:
python
google-cloud-firestore
crud
key-value
【解决方案1】:
我在网上找到零个现成的答案,并为我自己的用例编写了这个 Python 代码 sn-p,我在这里分享给其他人重复使用。
请阅读评论以了解其工作原理:
key = 'field'
key_nonexistent = 'field_nonexistent'
doc_ref = db.collection('test_coll').document('test_doc')
doc_ref.set({key: False})
# doc_ref.update({key_nonexistent: True}) # Will create 'field_nonexistent' -- not desired
dict_doc = doc_ref.get().to_dict()
if key in dict_doc.keys():
doc_ref.update(key: True) # Will update the field only if it exists -- desired
if key_nonexistent in dict_doc.keys():
doc_ref.update(key_nonexistent: not dict_doc[key_nonexistent]) # Proves the field won't be created if not existent. You can uncomment/comment out the commented line above to see how the result changes