Skip to content Skip to sidebar Skip to footer

How To Update A Field In A Firestore Document Only If It Exists (using Python)?

Firestore documentation explains you can use doc_ref.update({'key': 'value'}) to update a single field in a document (and create it if that field doesn't exist). The problem is: in

Solution 1:

I found zero ready-to-use answer on the internet and wrote this Python code snippet for my own use case, and I'm sharing here for others to reuse.

Please read the comment to see how it works:

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 -- desiredif 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

Post a Comment for "How To Update A Field In A Firestore Document Only If It Exists (using Python)?"