Pranay Ankit
Pranay Ankit

Reputation: 227

List all Firestore collections using Python admin SDK

I want to get all the collections stored in my Firestore database. I went through the documentation and found that getCollections() method on DocumentReference can be used if you're using Node.js server SDK. What's the Python equivalent of this?

Upvotes: 2

Views: 6947

Answers (2)

Frank van Puffelen
Frank van Puffelen

Reputation: 598688

The Python SDK has a Client.collections method that lists all top-level collections.

Once you have a document, you can get the subcollections of that by calling the DocumentReference.collections method.

Upvotes: 3

Cloudkollektiv
Cloudkollektiv

Reputation: 14669

I used this python snippet to go into top-level collection "my-collection" and find a document with a certain "id". Within that document i want to retrieve the documents of the last subcollection, since they contain the last version of the data that I am searching for.

fs = firestore_v1.Client()

collection = fs.collection("my-collection")
doc = collection.document("id")
sub_collections = doc.collections()
*_, last = sub_collections

sub_docs = last.stream()
for doc in sub_docs:
    print(doc.to_dict())

Note: you have to make a "dummy" entry within the top-level documents, otherwise there is no link between the root collection and the underlying subcollections.

Upvotes: 1

Related Questions