Obtener documentos de Firestore en colecciones anidadas
Organiza tus páginas con colecciones
Guarda y categoriza el contenido según tus preferencias.
Obtener documentos de Firestore en colecciones anidadas
Explora más
Para obtener documentación en la que se incluye esta muestra de código, consulta lo siguiente:
Muestra de código
Salvo que se indique lo contrario, el contenido de esta página está sujeto a la licencia Atribución 4.0 de Creative Commons, y los ejemplos de código están sujetos a la licencia Apache 2.0. Para obtener más información, consulta las políticas del sitio de Google Developers. Java es una marca registrada de Oracle o sus afiliados.
[[["Fácil de comprender","easyToUnderstand","thumb-up"],["Resolvió mi problema","solvedMyProblem","thumb-up"],["Otro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Información o código de muestra incorrectos","incorrectInformationOrSampleCode","thumb-down"],["Faltan la información o los ejemplos que necesito","missingTheInformationSamplesINeed","thumb-down"],["Problema de traducción","translationIssue","thumb-down"],["Otro","otherDown","thumb-down"]],[],[[["\u003cp\u003eThis content demonstrates how to retrieve and list subcollections within a Firestore document, using the "cities" collection as an example.\u003c/p\u003e\n"],["\u003cp\u003eThe code samples are provided in various languages, including C#, Go, Java, Node.js, PHP, Python, and Ruby, allowing developers to use the language they are most familiar with.\u003c/p\u003e\n"],["\u003cp\u003eEach code sample includes instructions to set up Application Default Credentials for Firestore authentication, pointing to a resource for setting up local development.\u003c/p\u003e\n"],["\u003cp\u003eThe document also provides links to the official Firebase documentation for further reading on retrieving data in Firestore.\u003c/p\u003e\n"]]],[],null,["# Get Firestore documents in nested collections\n\nExplore further\n---------------\n\n\nFor detailed documentation that includes this code sample, see the following:\n\n- [Get data with Cloud Firestore](https://firebase.google.com/docs/firestore/query-data/get-data)\n- [Getting data](/firestore/native/docs/query-data/get-data)\n\nCode sample\n-----------\n\n### C#\n\n\nTo authenticate to Firestore, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n DocumentReference cityRef = db.Collection(\"cities\").Document(\"SF\");\n IAsyncEnumerable\u003cCollectionReference\u003e subcollections = cityRef.ListCollectionsAsync();\n IAsyncEnumerator\u003cCollectionReference\u003e subcollectionsEnumerator = subcollections.GetAsyncEnumerator(default);\n while (await subcollectionsEnumerator.MoveNextAsync())\n {\n CollectionReference subcollectionRef = subcollectionsEnumerator.Current;\n Console.WriteLine(\"Found subcollection with ID: {0}\", subcollectionRef.Id);\n }\n\n### Go\n\n\nTo authenticate to Firestore, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n\n import (\n \t\"context\"\n \t\"fmt\"\n\n \t\"cloud.google.com/go/firestore\"\n \t\"google.golang.org/api/iterator\"\n )\n\n func getCollections(ctx context.Context, client *firestore.Client) error {\n \titer := client.Collection(\"cities\").Doc(\"SF\").Collections(ctx)\n \tfor {\n \t\tcollRef, err := iter.Next()\n \t\tif err == iterator.Done {\n \t\t\tbreak\n \t\t}\n \t\tif err != nil {\n \t\t\treturn err\n \t\t}\n \t\tfmt.Printf(\"Found collection with id: %s\\n\", collRef.ID)\n \t}\n \treturn nil\n }\n\n### Java\n\n\nTo authenticate to Firestore, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n Iterable\u003cCollectionReference\u003e collections =\n db.collection(\"cities\").document(\"SF\").listCollections();\n\n for (CollectionReference collRef : collections) {\n System.out.println(\"Found subcollection with id: \" + collRef.getId());\n }\n\n### Node.js\n\n\nTo authenticate to Firestore, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n const sfRef = db.collection('cities').doc('SF');\n const collections = await sfRef.listCollections();\n collections.forEach(collection =\u003e {\n console.log('Found subcollection with id:', collection.id);\n });\n\n### PHP\n\n\nTo authenticate to Firestore, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n $cityRef = $db-\u003ecollection('samples/php/cities')-\u003edocument('SF');\n $collections = $cityRef-\u003ecollections();\n foreach ($collections as $collection) {\n printf('Found subcollection with id: %s' . PHP_EOL, $collection-\u003eid());\n }\n\n### Python\n\n\nTo authenticate to Firestore, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n city_ref = db.collection(\"cities\").document(\"SF\")\n collections = city_ref.collections()\n for collection in collections:\n for doc in collection.stream():\n print(f\"{doc.id} =\u003e {doc.to_dict()}\")\n\n### Ruby\n\n\nTo authenticate to Firestore, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n city_ref = firestore.doc \"#{collection_path}/SF\"\n city_ref.cols do |col|\n puts col.collection_id\n end\n\nWhat's next\n-----------\n\n\nTo search and filter code samples for other Google Cloud products, see the\n[Google Cloud sample browser](/docs/samples?product=firestore)."]]