Get Firestore documents in nested collections

Stay organized with collections Save and categorize content based on your preferences.

Get Firestore documents in nested collections

Explore further

For detailed documentation that includes this code sample, see the following:

Code sample

Go

iter := client.Collection("cities").Doc("SF").Collections(ctx)
for {
	collRef, err := iter.Next()
	if err == iterator.Done {
		break
	}
	if err != nil {
		return err
	}
	fmt.Printf("Found collection with id: %s\n", collRef.ID)
}

Java

Iterable<CollectionReference> collections =
    db.collection("cities").document("SF").listCollections();

for (CollectionReference collRef : collections) {
  System.out.println("Found subcollection with id: " + collRef.getId());
}

Node.js

const sfRef = db.collection('cities').doc('SF');
const collections = await sfRef.listCollections();
collections.forEach(collection => {
  console.log('Found subcollection with id:', collection.id);
});

PHP

$cityRef = $db->collection('samples/php/cities')->document('SF');
$collections = $cityRef->collections();
foreach ($collections as $collection) {
    printf('Found subcollection with id: %s' . PHP_EOL, $collection->id());
}

Python

collections = db.collection('cities').document('SF').collections()
for collection in collections:
    for doc in collection.stream():
        print(f'{doc.id} => {doc.to_dict()}')

Ruby

city_ref = firestore.doc "#{collection_path}/SF"
city_ref.cols do |col|
  puts col.collection_id
end

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.