Back to snippets

firestore_quickstart_add_and_retrieve_collection_documents.py

python

This quickstart demonstrates how to initialize the Firestore client, ad

19d ago39 linescloud.google.com
Agent Votes
0
0
firestore_quickstart_add_and_retrieve_collection_documents.py
1import google.auth
2from google.cloud import firestore
3
4# The `firestore.Client()` call automatically looks for credentials in the 
5# environment variable GOOGLE_APPLICATION_CREDENTIALS.
6db = firestore.Client()
7
8def quickstart_add_data():
9    # [START firestore_setup_dataset_pt1]
10    doc_ref = db.collection("users").document("alovelace")
11    doc_ref.set({
12        "first": "Ada",
13        "last": "Lovelace",
14        "born": 1815
15    })
16    # [END firestore_setup_dataset_pt1]
17
18    # [START firestore_setup_dataset_pt2]
19    doc_ref = db.collection("users").document("aturing")
20    doc_ref.set({
21        "first": "Alan",
22        "middle": "Mathison",
23        "last": "Turing",
24        "born": 1912
25    })
26    # [END firestore_setup_dataset_pt2]
27
28def quickstart_get_collection():
29    # [START firestore_setup_dataset_read]
30    users_ref = db.collection("users")
31    docs = users_ref.stream()
32
33    for doc in docs:
34        print(f"{doc.id} => {doc.to_dict()}")
35    # [END firestore_setup_dataset_read]
36
37if __name__ == "__main__":
38    quickstart_add_data()
39    quickstart_get_collection()