Stay organized with collectionsSave and categorize content based on your preferences.
Getting data
There are three ways to retrieve data stored in Firestore. Any of
these methods can be used with documents, collections of documents, or the
results of queries:
Call a method to get the data once.
Set a listener to receive data-change events.
Bulk-load Firestore snapshot data from an external source viadata bundles. See the bundles doc for more
details.
When you set a listener, Firestore sends your listener an initial
snapshot of the data, and then another snapshot each time the document changes.
fromgoogle.cloudimportfirestore# The `project` parameter is optional and represents which project the client# will act on behalf of. If not supplied, the client falls back to the default# project inferred from the environment.db=firestore.Client(project="my-project-id")
fromgoogle.cloudimportfirestore# The `project` parameter is optional and represents which project the client# will act on behalf of. If not supplied, the client falls back to the default# project inferred from the environment.db=firestore.AsyncClient(project="my-project-id")
import("context""flag""fmt""log""google.golang.org/api/iterator""cloud.google.com/go/firestore")funccreateClient(ctxcontext.Context)*firestore.Client{// Sets your Google Cloud Platform project ID.projectID:="YOUR_PROJECT_ID"client,err:=firestore.NewClient(ctx,projectID)iferr!=nil{log.Fatalf("Failed to create client: %v",err)}// Close client when done with// defer client.Close()returnclient}
use Google\Cloud\Firestore\FirestoreClient;/*** Initialize Cloud Firestore with default project ID.*/function setup_client_create(string $projectId = null){// Create the Cloud Firestore clientif (empty($projectId)) {// The `projectId` parameter is optional and represents which project the// client will act on behalf of. If not supplied, the client falls back to// the default project inferred from the environment.$db = new FirestoreClient();printf('Created Cloud Firestore client with default project ID.' . PHP_EOL);} else {$db = new FirestoreClient(['projectId' => $projectId,]);printf('Created Cloud Firestore client with project ID: %s' . PHP_EOL, $projectId);}}
FirestoreDbdb=FirestoreDb.Create(project);Console.WriteLine("Created Cloud Firestore client with project ID: {0}",project);
Ruby
require"google/cloud/firestore"# The `project_id` parameter is optional and represents which project the# client will act on behalf of. If not supplied, the client falls back to the# default project inferred from the environment.firestore=Google::Cloud::Firestore.newproject_id:project_idputs"Created Cloud Firestore client with given project ID."
CollectionReferencecitiesRef=db.Collection("cities");awaitcitiesRef.Document("SF").SetAsync(newDictionary<string,object>(){{"Name","San Francisco"},{"State","CA"},{"Country","USA"},{"Capital",false},{"Population",860000}});awaitcitiesRef.Document("LA").SetAsync(newDictionary<string,object>(){{"Name","Los Angeles"},{"State","CA"},{"Country","USA"},{"Capital",false},{"Population",3900000}});awaitcitiesRef.Document("DC").SetAsync(newDictionary<string,object>(){{"Name","Washington D.C."},{"State",null},{"Country","USA"},{"Capital",true},{"Population",680000}});awaitcitiesRef.Document("TOK").SetAsync(newDictionary<string,object>(){{"Name","Tokyo"},{"State",null},{"Country","Japan"},{"Capital",true},{"Population",9000000}});awaitcitiesRef.Document("BJ").SetAsync(newDictionary<string,object>(){{"Name","Beijing"},{"State",null},{"Country","China"},{"Capital",true},{"Population",21500000}});Console.WriteLine("Added example cities data to the cities collection.");
The following example shows how to retrieve the contents of a single document
usingget():
Web version 9
import{doc,getDoc}from"firebase/firestore";constdocRef=doc(db,"cities","SF");constdocSnap=awaitgetDoc(docRef);if(docSnap.exists()){console.log("Document data:",docSnap.data());}else{// docSnap.data() will be undefined in this caseconsole.log("No such document!");}
vardocRef=db.collection("cities").doc("SF");docRef.get().then((doc)=>{if(doc.exists){console.log("Document data:",doc.data());}else{// doc.data() will be undefined in this caseconsole.log("No such document!");}}).catch((error)=>{console.log("Error getting document:",error);});
Note:This product is not available on watchOS and App Clip targets.
letdocRef=db.collection("cities").document("SF")do{letdocument=tryawaitdocRef.getDocument()ifdocument.exists{letdataDescription=document.data().map(String.init(describing:))??"nil"print("Document data:\(dataDescription)")}else{print("Document does not exist")}}catch{print("Error getting document:\(error)")}
Note:This product is not available on watchOS and App Clip targets.
FIRDocumentReference*docRef=[[self.dbcollectionWithPath:@"cities"]documentWithPath:@"SF"];[docRefgetDocumentWithCompletion:^(FIRDocumentSnapshot*snapshot,NSError*error){if(snapshot.exists){// Document data may be nil if the document exists but has no keys or values.NSLog(@"Document data: %@",snapshot.data);}else{NSLog(@"Document does not exist");}}];
valdocRef=db.collection("cities").document("SF")docRef.get().addOnSuccessListener{document->if(document!=null){Log.d(TAG,"DocumentSnapshot data:${document.data}")}else{Log.d(TAG,"No such document")}}.addOnFailureListener{exception->Log.d(TAG,"get failed with ",exception)}
DocumentReferencedocRef=db.collection("cities").document("SF");docRef.get().addOnCompleteListener(newOnCompleteListener<DocumentSnapshot>(){@OverridepublicvoidonComplete(@NonNullTask<DocumentSnapshot>task){if(task.isSuccessful()){DocumentSnapshotdocument=task.getResult();if(document.exists()){Log.d(TAG,"DocumentSnapshot data: "+document.getData());}else{Log.d(TAG,"No such document");}}else{Log.d(TAG,"get failed with ",task.getException());}}});
DocumentReferencedocRef=db.collection("cities").document("SF");// asynchronously retrieve the documentApiFuture<DocumentSnapshot>future=docRef.get();// ...// future.get() blocks on responseDocumentSnapshotdocument=future.get();if(document.exists()){System.out.println("Document data: "+document.getData());}else{System.out.println("No such document!");}
doc_ref=db.collection("cities").document("SF")doc=awaitdoc_ref.get()ifdoc.exists:print(f"Document data:{doc.to_dict()}")else:print("No such document!")
constcityRef=db.collection('cities').doc('SF');constdoc=awaitcityRef.get();if(!doc.exists){console.log('No such document!');}else{console.log('Document data:',doc.data());}
$docRef = $db->collection('samples/php/cities')->document('SF');$snapshot = $docRef->snapshot();if ($snapshot->exists()) {printf('Document data:' . PHP_EOL);print_r($snapshot->data());} else {printf('Document %s does not exist!' . PHP_EOL, $snapshot->id());}
Unity
DocumentReferencedocRef=db.Collection("cities").Document("SF");docRef.GetSnapshotAsync().ContinueWithOnMainThread(task=>{DocumentSnapshotsnapshot=task.Result;if(snapshot.Exists){Debug.Log(String.Format("Document data for {0} document:",snapshot.Id));Dictionary<string,object>city=snapshot.ToDictionary();foreach(KeyValuePair<string,object>pairincity){Debug.Log(String.Format("{0}: {1}",pair.Key,pair.Value));}}else{Debug.Log(String.Format("Document {0} does not exist!",snapshot.Id));}});
C#
DocumentReferencedocRef=db.Collection("cities").Document("SF");DocumentSnapshotsnapshot=awaitdocRef.GetSnapshotAsync();if(snapshot.Exists){Console.WriteLine("Document data for {0} document:",snapshot.Id);Dictionary<string,object>city=snapshot.ToDictionary();foreach(KeyValuePair<string,object>pairincity){Console.WriteLine("{0}: {1}",pair.Key,pair.Value);}}else{Console.WriteLine("Document {0} does not exist!",snapshot.Id);}
doc_ref=firestore.doc"#{collection_path}/SF"snapshot=doc_ref.getifsnapshot.exists?puts"#{snapshot.document_id}data:#{snapshot.data}."elseputs"Document#{snapshot.document_id}does not exist!"end
For platforms with offline support, you can set thesourceoption to control
how agetcall uses the offline cache.
By default, agetcall will attempt to fetch the latest document snapshot from
your database. On platforms with offline support, the client library will use
the offline cache if the network is unavailable or if the request times out.
You can specify thesourceoption in aget()call to change
the default behavior. You can fetch from only the database and ignore
the offline cache, or you can fetch from only the offline cache. For example:
Web version 9
import{doc,getDocFromCache}from"firebase/firestore";constdocRef=doc(db,"cities","SF");// Get a document, forcing the SDK to fetch from the offline cache.try{constdoc=awaitgetDocFromCache(docRef);// Document was found in the cache. If no cached document exists,// an error will be returned to the 'catch' block below.console.log("Cached document data:",doc.data());}catch(e){console.log("Error getting cached document:",e);}
vardocRef=db.collection("cities").doc("SF");// Valid options for source are 'server', 'cache', or// 'default'. See https://firebase.google.com/docs/reference/js/v8/firebase.firestore.GetOptions// for more information.vargetOptions={source:'cache'};// Get a document, forcing the SDK to fetch from the offline cache.docRef.get(getOptions).then((doc)=>{// Document was found in the cache. If no cached document exists,// an error will be returned to the 'catch' block below.console.log("Cached document data:",doc.data());}).catch((error)=>{console.log("Error getting cached document:",error);});
Note:This product is not available on watchOS and App Clip targets.
letdocRef=db.collection("cities").document("SF")do{// Force the SDK to fetch the document from the cache. Could also specify// FirestoreSource.server or FirestoreSource.default.letdocument=tryawaitdocRef.getDocument(source:.cache)ifdocument.exists{letdataDescription=document.data().map(String.init(describing:))??"nil"print("Cached document data:\(dataDescription)")}else{print("Document does not exist in cache")}}catch{print("Error getting document:\(error)")}
Note:This product is not available on watchOS and App Clip targets.
FIRDocumentReference*docRef=[[self.dbcollectionWithPath:@"cities"]documentWithPath:@"SF"];// Force the SDK to fetch the document from the cache. Could also specify// FIRFirestoreSourceServer or FIRFirestoreSourceDefault.[docRefgetDocumentWithSource:FIRFirestoreSourceCachecompletion:^(FIRDocumentSnapshot*snapshot,NSError*error){if(snapshot!=NULL){// The document data was found in the cache.NSLog(@"Cached document data: %@",snapshot.data);}else{// The document data was not found in the cache.NSLog(@"Document does not exist in cache: %@",error);}}];
valdocRef=db.collection("cities").document("SF")// Source can be CACHE, SERVER, or DEFAULT.valsource=Source.CACHE// Get the document, forcing the SDK to use the offline cachedocRef.get(source).addOnCompleteListener{task->if(task.isSuccessful){// Document found in the offline cachevaldocument=task.resultLog.d(TAG,"Cached document data:${document?.data}")}else{Log.d(TAG,"Cached get failed: ",task.exception)}}
DocumentReferencedocRef=db.collection("cities").document("SF");// Source can be CACHE, SERVER, or DEFAULT.Sourcesource=Source.CACHE;// Get the document, forcing the SDK to use the offline cachedocRef.get(source).addOnCompleteListener(newOnCompleteListener<DocumentSnapshot>(){@OverridepublicvoidonComplete(@NonNullTask<DocumentSnapshot>task){if(task.isSuccessful()){// Document found in the offline cacheDocumentSnapshotdocument=task.getResult();Log.d(TAG,"Cached document data: "+document.getData());}else{Log.d(TAG,"Cached get failed: ",task.getException());}}});
finaldocRef=db.collection("cities").doc("SF");// Source can be CACHE, SERVER, or DEFAULT.constsource=Source.cache;docRef.get(constGetOptions(source:source)).then((res)=>print("Successfully completed"),onError:(e)=>print("Error completing:$e"),);
The previous example retrieved the contents of the
document as a map, but in some languages it's often more convenient to use a
custom object type. InAdd Data, you defined aCityclass
that you used to define each city. You can turn your document back into aCityobject:
To use custom objects, you must define aFirestoreDataConverterfunction for your class. For example:
Web version 9
classCity{constructor(name,state,country){this.name=name;this.state=state;this.country=country;}toString(){returnthis.name+', '+this.state+', '+this.country;}}// Firestore data converterconstcityConverter={toFirestore:(city)=>{return{name:city.name,state:city.state,country:city.country};},fromFirestore:(snapshot,options)=>{constdata=snapshot.data(options);returnnewCity(data.name,data.state,data.country);}};
Call your data converter with your read operations. After conversion, you can
access custom object methods:
Web version 9
import{doc,getDoc}from"firebase/firestore";constref=doc(db,"cities","LA").withConverter(cityConverter);constdocSnap=awaitgetDoc(ref);if(docSnap.exists()){// Convert to City objectconstcity=docSnap.data();// Use a City instance methodconsole.log(city.toString());}else{console.log("No such document!");}
Call your data converter with your read operations. After conversion, you can
access custom object methods:
Web version 8
db.collection("cities").doc("LA").withConverter(cityConverter).get().then((doc)=>{if(doc.exists){// Convert to City objectvarcity=doc.data();// Use a City instance methodconsole.log(city.toString());}else{console.log("No such document!");}}).catch((error)=>{console.log("Error getting document:",error);});
Note:This product is not available on watchOS and App Clip targets.
In Objective-C you must do this manually.
FIRDocumentReference*docRef=[[self.dbcollectionWithPath:@"cities"]documentWithPath:@"BJ"];[docRefgetDocumentWithCompletion:^(FIRDocumentSnapshot*snapshot,NSError*error){FSTCity*city=[[FSTCityalloc]initWithDictionary:snapshot.data];if(city!=nil){NSLog(@"City: %@",city);}else{NSLog(@"Document does not exist");}}];
Important: Each custom class must have a public constructor that takes no
arguments. In addition, the class must include a public getter for each
property.
Then, create a document reference with your data conversion functions. Any
read operations you perform using this reference will return instances of
your custom class:
finalref=db.collection("cities").doc("LA").withConverter(fromFirestore:City.fromFirestore,toFirestore:(Citycity,_)=>city.toFirestore(),);finaldocSnap=awaitref.get();finalcity=docSnap.data();// Convert to City objectif(city!=null){print(city);}else{print("No such document.");}
Each custom class must have a public constructor that takes no
arguments. In addition, the class must include a public getter for each
property.
DocumentReferencedocRef=db.collection("cities").document("BJ");// asynchronously retrieve the documentApiFuture<DocumentSnapshot>future=docRef.get();// block on responseDocumentSnapshotdocument=future.get();Citycity=null;if(document.exists()){// convert document to POJOcity=document.toObject(City.class);System.out.println(city);}else{System.out.println("No such document!");}
DocumentReferencedocRef=db.Collection("cities").Document("BJ");docRef.GetSnapshotAsync().ContinueWith((task)=>{varsnapshot=task.Result;if(snapshot.Exists){Debug.Log(String.Format("Document data for {0} document:",snapshot.Id));Citycity=snapshot.ConvertTo<City>();Debug.Log(String.Format("Name: {0}",city.Name));Debug.Log(String.Format("State: {0}",city.State));Debug.Log(String.Format("Country: {0}",city.Country));Debug.Log(String.Format("Capital: {0}",city.Capital));Debug.Log(String.Format("Population: {0}",city.Population));}else{Debug.Log(String.Format("Document {0} does not exist!",snapshot.Id));}});
C#
DocumentReferencedocRef=db.Collection("cities").Document("BJ");DocumentSnapshotsnapshot=awaitdocRef.GetSnapshotAsync();if(snapshot.Exists){Console.WriteLine("Document data for {0} document:",snapshot.Id);Citycity=snapshot.ConvertTo<City>();Console.WriteLine("Name: {0}",city.Name);Console.WriteLine("State: {0}",city.State);Console.WriteLine("Country: {0}",city.Country);Console.WriteLine("Capital: {0}",city.Capital);Console.WriteLine("Population: {0}",city.Population);}else{Console.WriteLine("Document {0} does not exist!",snapshot.Id);}
You can also retrieve multiple documents with one request by querying documents
in a collection. For example, you can usewhere()to query for all of the
documents that meet a certain condition, then useget()to retrieve the
results:
Web version 9
import{collection,query,where,getDocs}from"firebase/firestore";constq=query(collection(db,"cities"),where("capital","==",true));constquerySnapshot=awaitgetDocs(q);querySnapshot.forEach((doc)=>{// doc.data() is never undefined for query doc snapshotsconsole.log(doc.id," => ",doc.data());});
db.collection("cities").where("capital","==",true).get().then((querySnapshot)=>{querySnapshot.forEach((doc)=>{// doc.data() is never undefined for query doc snapshotsconsole.log(doc.id," => ",doc.data());});}).catch((error)=>{console.log("Error getting documents: ",error);});
# Note: Use of CollectionRef stream() is prefered to get()docs=(db.collection("cities").where(filter=FieldFilter("capital","==",True)).stream())fordocindocs:print(f"{doc.id}=>{doc.to_dict()}")
# Note: Use of CollectionRef stream() is prefered to get()docs=(db.collection("cities").where(filter=FieldFilter("capital","==",True)).stream())asyncfordocindocs:print(f"{doc.id}=>{doc.to_dict()}")
import("context""fmt""cloud.google.com/go/firestore""google.golang.org/api/iterator")funcmultipleDocs(ctxcontext.Context,client*firestore.Client)error{fmt.Println("All capital cities:")iter:=client.Collection("cities").Where("capital","==",true).Documents(ctx)for{doc,err:=iter.Next()iferr==iterator.Done{break}iferr!=nil{returnerr}fmt.Println(doc.Data())}returnnil}
$citiesRef = $db->collection('samples/php/cities');$query = $citiesRef->where('capital', '=', true);$documents = $query->documents();foreach ($documents as $document) {if ($document->exists()) {printf('Document data for document %s:' . PHP_EOL, $document->id());print_r($document->data());printf(PHP_EOL);} else {printf('Document %s does not exist!' . PHP_EOL, $document->id());}}
Unity
QuerycapitalQuery=db.Collection("cities").WhereEqualTo("Capital",true);capitalQuery.GetSnapshotAsync().ContinueWithOnMainThread(task=>{QuerySnapshotcapitalQuerySnapshot=task.Result;foreach(DocumentSnapshotdocumentSnapshotincapitalQuerySnapshot.Documents){Debug.Log(String.Format("Document data for {0} document:",documentSnapshot.Id));Dictionary<string,object>city=documentSnapshot.ToDictionary();foreach(KeyValuePair<string,object>pairincity){Debug.Log(String.Format("{0}: {1}",pair.Key,pair.Value));}// Newline to separate entriesDebug.Log("");};});
C#
QuerycapitalQuery=db.Collection("cities").WhereEqualTo("Capital",true);QuerySnapshotcapitalQuerySnapshot=awaitcapitalQuery.GetSnapshotAsync();foreach(DocumentSnapshotdocumentSnapshotincapitalQuerySnapshot.Documents){Console.WriteLine("Document data for {0} document:",documentSnapshot.Id);Dictionary<string,object>city=documentSnapshot.ToDictionary();foreach(KeyValuePair<string,object>pairincity){Console.WriteLine("{0}: {1}",pair.Key,pair.Value);}Console.WriteLine("");}
By default, Firestore retrieves all documents that satisfy the
query in ascending order by document ID, but you canorder and limit the data
returned.
Get all documents in a collection
In addition, you can retrievealldocuments in a collection by omitting thewhere()filter entirely:
Web version 9
import{collection,getDocs}from"firebase/firestore";constquerySnapshot=awaitgetDocs(collection(db,"cities"));querySnapshot.forEach((doc)=>{// doc.data() is never undefined for query doc snapshotsconsole.log(doc.id," => ",doc.data());});
db.collection("cities").get().then((querySnapshot)=>{querySnapshot.forEach((doc)=>{// doc.data() is never undefined for query doc snapshotsconsole.log(doc.id," => ",doc.data());});});
$citiesRef = $db->collection('samples/php/cities');$documents = $citiesRef->documents();foreach ($documents as $document) {if ($document->exists()) {printf('Document data for document %s:' . PHP_EOL, $document->id());print_r($document->data());printf(PHP_EOL);} else {printf('Document %s does not exist!' . PHP_EOL, $document->id());}}
Unity
QueryallCitiesQuery=db.Collection("cities");allCitiesQuery.GetSnapshotAsync().ContinueWithOnMainThread(task=>{QuerySnapshotallCitiesQuerySnapshot=task.Result;foreach(DocumentSnapshotdocumentSnapshotinallCitiesQuerySnapshot.Documents){Debug.Log(String.Format("Document data for {0} document:",documentSnapshot.Id));Dictionary<string,object>city=documentSnapshot.ToDictionary();foreach(KeyValuePair<string,object>pairincity){Debug.Log(String.Format("{0}: {1}",pair.Key,pair.Value));}// Newline to separate entriesDebug.Log("");}});
C#
QueryallCitiesQuery=db.Collection("cities");QuerySnapshotallCitiesQuerySnapshot=awaitallCitiesQuery.GetSnapshotAsync();foreach(DocumentSnapshotdocumentSnapshotinallCitiesQuerySnapshot.Documents){Console.WriteLine("Document data for {0} document:",documentSnapshot.Id);Dictionary<string,object>city=documentSnapshot.ToDictionary();foreach(KeyValuePair<string,object>pairincity){Console.WriteLine("{0}: {1}",pair.Key,pair.Value);}Console.WriteLine("");}
To retrieve all the documents from a subcollection, create a reference with the
complete path to that subcollection:
Web version 9
const{collection,getDocs}=require("firebase/firestore");// Query a reference to a subcollectionconstquerySnapshot=awaitgetDocs(collection(db,"cities","SF","landmarks"));querySnapshot.forEach((doc)=>{// doc.data() is never undefined for query doc snapshotsconsole.log(doc.id," => ",doc.data());});
A collection group consists of all collections with the same ID. For example, if
each document in yourcitiescollection has a subcollection calledlandmarks, all of thelandmarkssubcollections belong to the same collection
group. By default, queries retrieve results from a single collection in your
database.Use a collection group query to retrieve results from a collection
groupinstead of from a single collection.
List subcollections of a document
ThelistCollections()method of the Firestore server client libraries
lists all subcollections of a document reference.
Retrieving a list of collections is not possible with the mobile/web client libraries.
You should only look up collection names as part of administrative tasks
in trusted server environments. If you find that you need this capability
in the mobile/web client libraries, consider restructuring your data so that
subcollection names are predictable.
Web
Not available in the Web client library.
Swift
Not available in the Swift client library.
Objective-C
Not available in the Objective-C client library.
Kotlin Android
Not available in the Android client library.
Java Android
Not available in the Android client library.
Dart
Not available in the Flutter client library.
Java
Iterable<CollectionReference>collections=db.collection("cities").document("SF").listCollections();for(CollectionReferencecollRef:collections){System.out.println("Found subcollection with id: "+collRef.getId());}
constsfRef=db.collection('cities').doc('SF');constcollections=awaitsfRef.listCollections();collections.forEach(collection=>{console.log('Found subcollection with id:',collection.id);});
import("context""fmt""cloud.google.com/go/firestore""google.golang.org/api/iterator")funcgetCollections(ctxcontext.Context,client*firestore.Client)error{iter:=client.Collection("cities").Doc("SF").Collections(ctx)for{collRef,err:=iter.Next()iferr==iterator.Done{break}iferr!=nil{returnerr}fmt.Printf("Found collection with id: %s\n",collRef.ID)}returnnil}
$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());}
Unity
// This is not yet supported in the Unity SDK.
C#
DocumentReferencecityRef=db.Collection("cities").Document("SF");IAsyncEnumerable<CollectionReference>subcollections=cityRef.ListCollectionsAsync();IAsyncEnumerator<CollectionReference>subcollectionsEnumerator=subcollections.GetAsyncEnumerator(default);while(awaitsubcollectionsEnumerator.MoveNextAsync()){CollectionReferencesubcollectionRef=subcollectionsEnumerator.Current;Console.WriteLine("Found subcollection with ID: {0}",subcollectionRef.Id);}
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Hard to understand","hardToUnderstand","thumb-down"],["Incorrect information or sample code","incorrectInformationOrSampleCode","thumb-down"],["Missing the information/samples I need","missingTheInformationSamplesINeed","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2025-09-04 UTC."],[],[],null,[]]