Get data with Cloud Firestore Stay organized with collections Save and categorize content based on your preferences.
There are three ways to retrieve data stored inCloud Firestore. Any ofthese methods can be used with documents, collections of documents, or theresults 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 moredetails.
When you set a listener,Cloud Firestore sends your listener an initialsnapshot of the data, and then another snapshot each time the document changes.
Note: While the code samples cover multiple languages, the text explaining thesamples refers to the Web method names.Before you begin
SeeGet started withCloud Firestore tocreate aCloud Firestore database.InitializeCloud Firestore
Initialize an instance ofCloud Firestore:
Web
import{initializeApp}from"firebase/app";import{getFirestore}from"firebase/firestore";//TODO:Replacethefollowingwithyourapp's Firebase project configuration//See:https://support.google.com/firebase/answer/7015592constfirebaseConfig={FIREBASE_CONFIGURATION};//InitializeFirebaseconstapp=initializeApp(firebaseConfig);//InitializeCloudFirestoreandgetareferencetotheserviceconstdb=getFirestore(app);
ReplaceFIREBASE_CONFIGURATION with your web app'sfirebaseConfig.
To persist data when the device loses its connection, see theEnable Offline Data documentation.
Web
importfirebasefrom"firebase/app";import"firebase/firestore";//TODO:Replacethefollowingwithyourapp's Firebase project configuration//See:https://support.google.com/firebase/answer/7015592constfirebaseConfig={FIREBASE_CONFIGURATION};//InitializeFirebasefirebase.initializeApp(firebaseConfig);//InitializeCloudFirestoreandgetareferencetotheserviceconstdb=firebase.firestore();
ReplaceFIREBASE_CONFIGURATION with your web app'sfirebaseConfig.
To persist data when the device loses its connection, see theEnable Offline Data documentation.
Swift
importFirebaseCoreimportFirebaseFirestore
FirebaseApp.configure()letdb=Firestore.firestore()
Objective-C
@importFirebaseCore;@importFirebaseFirestore;//UseFirebaselibrarytoconfigureAPIs[FIRAppconfigure];
FIRFirestore*defaultFirestore=[FIRFirestorefirestore];
Kotlin
// Access aCloud Firestore instance from your Activityvaldb=Firebase.firestore
Java
// Access aCloud Firestore instance from your ActivityFirebaseFirestoredb=FirebaseFirestore.getInstance();
Dart
db=FirebaseFirestore.instance;
Java
TheCloud Firestore SDK is initialized in different ways depending onyour environment. Below are the most common methods. For a complete reference,seeInitializethe Admin SDK.importcom.google.auth.oauth2.GoogleCredentials;importcom.google.cloud.firestore.Firestore;importcom.google.firebase.FirebaseApp;importcom.google.firebase.FirebaseOptions;// Use the application default credentialsGoogleCredentialscredentials=GoogleCredentials.getApplicationDefault();FirebaseOptionsoptions=newFirebaseOptions.Builder().setCredentials(credentials).setProjectId(projectId).build();FirebaseApp.initializeApp(options);Firestoredb=FirestoreClient.getFirestore();
To use the Firebase Admin SDK on your own server, use aservice account.
Go toIAM & admin > Service accounts in the Google Cloud console. Generate a new private key and save the JSON file. Then use the file to initialize the SDK:
importcom.google.auth.oauth2.GoogleCredentials;importcom.google.cloud.firestore.Firestore;importcom.google.firebase.FirebaseApp;importcom.google.firebase.FirebaseOptions;// Use a service accountInputStreamserviceAccount=newFileInputStream("path/to/serviceAccount.json");GoogleCredentialscredentials=GoogleCredentials.fromStream(serviceAccount);FirebaseOptionsoptions=newFirebaseOptions.Builder().setCredentials(credentials).build();FirebaseApp.initializeApp(options);Firestoredb=FirestoreClient.getFirestore();
Python
TheCloud Firestore SDK is initialized in different ways depending onyour environment. Below are the most common methods. For a complete reference,seeInitializethe Admin SDK.importfirebase_adminfromfirebase_adminimportfirestore# Application Default credentials are automatically created.app=firebase_admin.initialize_app()db=firestore.client()
An existing application default credential can also be used to initialize the SDK.
importfirebase_adminfromfirebase_adminimportcredentialsfromfirebase_adminimportfirestore# Use the application default credentials.cred=credentials.ApplicationDefault()firebase_admin.initialize_app(cred)db=firestore.client()
To use the Firebase Admin SDK on your own server, use aservice account.
Go toIAM & admin > Service accounts in the Google Cloud console. Generate a new private key and save the JSON file. Then use the file to initialize the SDK:
importfirebase_adminfromfirebase_adminimportcredentialsfromfirebase_adminimportfirestore# Use a service account.cred=credentials.Certificate('path/to/serviceAccount.json')app=firebase_admin.initialize_app(cred)db=firestore.client()
Python
TheCloud Firestore SDK is initialized in different ways depending onyour environment. Below are the most common methods. For a complete reference,seeInitializethe Admin SDK.importfirebase_adminfromfirebase_adminimportfirestore_async# Application Default credentials are automatically created.app=firebase_admin.initialize_app()db=firestore_async.client()
An existing application default credential can also be used to initialize the SDK.
importfirebase_adminfromfirebase_adminimportcredentialsfromfirebase_adminimportfirestore_async# Use the application default credentials.cred=credentials.ApplicationDefault()firebase_admin.initialize_app(cred)db=firestore_async.client()
To use the Firebase Admin SDK on your own server, use aservice account.
Go toIAM & admin > Service accounts in the Google Cloud console. Generate a new private key and save the JSON file. Then use the file to initialize the SDK:
importfirebase_adminfromfirebase_adminimportcredentialsfromfirebase_adminimportfirestore_async# Use a service account.cred=credentials.Certificate('path/to/serviceAccount.json')app=firebase_admin.initialize_app(cred)db=firestore_async.client()
C++
// Make sure the call to `Create()` happens some time before you call Firestore::GetInstance().App::Create();Firestore*db=Firestore::GetInstance();
Node.js
TheCloud Firestore SDK is initialized in different ways depending onyour environment. Below are the most common methods. For a complete reference,seeInitializethe Admin SDK.- Initialize onCloud Functions
const{initializeApp,applicationDefault,cert}=require('firebase-admin/app');const{getFirestore,Timestamp,FieldValue,Filter}=require('firebase-admin/firestore');
initializeApp();constdb=getFirestore();
- Initialize onGoogle Cloud
const{initializeApp,applicationDefault,cert}=require('firebase-admin/app');const{getFirestore,Timestamp,FieldValue,Filter}=require('firebase-admin/firestore');
initializeApp({credential:applicationDefault()});constdb=getFirestore();
- Initialize on your own server
To use the Firebase Admin SDK on your own server (or any other Node.js environment),use aservice account.Go toIAM & admin > Service accounts in the Google Cloud console. Generate a new private key and save the JSON file. Then use the file to initialize the SDK:
const{initializeApp,applicationDefault,cert}=require('firebase-admin/app');const{getFirestore,Timestamp,FieldValue,Filter}=require('firebase-admin/firestore');
constserviceAccount=require('./path/to/serviceAccountKey.json');initializeApp({credential:cert(serviceAccount)});constdb=getFirestore();
Go
TheCloud Firestore SDK is initialized in different ways depending onyour environment. Below are the most common methods. For a complete reference,seeInitializethe Admin SDK.import("log"firebase"firebase.google.com/go""google.golang.org/api/option")// Use the application default credentialsctx:=context.Background()conf:=&firebase.Config{ProjectID:projectID}app,err:=firebase.NewApp(ctx,conf)iferr!=nil{log.Fatalln(err)}client,err:=app.Firestore(ctx)iferr!=nil{log.Fatalln(err)}deferclient.Close()
To use the Firebase Admin SDK on your own server, use aservice account.
Go toIAM & admin > Service accounts in the Google Cloud console. Generate a new private key and save the JSON file. Then use the file to initialize the SDK:
import("log"firebase"firebase.google.com/go""google.golang.org/api/option")// Use a service accountctx:=context.Background()sa:=option.WithCredentialsFile("path/to/serviceAccount.json")app,err:=firebase.NewApp(ctx,nil,sa)iferr!=nil{log.Fatalln(err)}client,err:=app.Firestore(ctx)iferr!=nil{log.Fatalln(err)}deferclient.Close()
PHP
PHP
For more on installing and creating aCloud Firestore client, refer toCloud Firestore Client Libraries.
use Google\Cloud\Firestore\FirestoreClient;/** * Initialize Cloud Firestore with default project ID. */function setup_client_create(string $projectId = null){ // Create the Cloud Firestore client if (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); }}Unity
usingFirebase.Firestore;usingFirebase.Extensions;
FirebaseFirestoredb=FirebaseFirestore.DefaultInstance;
C#
C#
For more on installing and creating aCloud Firestore client, refer toCloud Firestore Client Libraries.
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."Example data
To get started, write some data about cities so we can look at different ways toread it back:
Web
import{collection,doc,setDoc}from"firebase/firestore";constcitiesRef=collection(db,"cities");awaitsetDoc(doc(citiesRef,"SF"),{name:"San Francisco",state:"CA",country:"USA",capital:false,population:860000,regions:["west_coast","norcal"]});awaitsetDoc(doc(citiesRef,"LA"),{name:"Los Angeles",state:"CA",country:"USA",capital:false,population:3900000,regions:["west_coast","socal"]});awaitsetDoc(doc(citiesRef,"DC"),{name:"Washington, D.C.",state:null,country:"USA",capital:true,population:680000,regions:["east_coast"]});awaitsetDoc(doc(citiesRef,"TOK"),{name:"Tokyo",state:null,country:"Japan",capital:true,population:9000000,regions:["kanto","honshu"]});awaitsetDoc(doc(citiesRef,"BJ"),{name:"Beijing",state:null,country:"China",capital:true,population:21500000,regions:["jingjinji","hebei"]});
Web
Learn more about the tree-shakeable modular Web API and its advantages over the namespaced API.varcitiesRef=db.collection("cities");citiesRef.doc("SF").set({name:"San Francisco",state:"CA",country:"USA",capital:false,population:860000,regions:["west_coast","norcal"]});citiesRef.doc("LA").set({name:"Los Angeles",state:"CA",country:"USA",capital:false,population:3900000,regions:["west_coast","socal"]});citiesRef.doc("DC").set({name:"Washington, D.C.",state:null,country:"USA",capital:true,population:680000,regions:["east_coast"]});citiesRef.doc("TOK").set({name:"Tokyo",state:null,country:"Japan",capital:true,population:9000000,regions:["kanto","honshu"]});citiesRef.doc("BJ").set({name:"Beijing",state:null,country:"China",capital:true,population:21500000,regions:["jingjinji","hebei"]});
Swift
letcitiesRef=db.collection("cities")citiesRef.document("SF").setData(["name":"San Francisco","state":"CA","country":"USA","capital":false,"population":860000,"regions":["west_coast","norcal"]])citiesRef.document("LA").setData(["name":"Los Angeles","state":"CA","country":"USA","capital":false,"population":3900000,"regions":["west_coast","socal"]])citiesRef.document("DC").setData(["name":"Washington D.C.","country":"USA","capital":true,"population":680000,"regions":["east_coast"]])citiesRef.document("TOK").setData(["name":"Tokyo","country":"Japan","capital":true,"population":9000000,"regions":["kanto","honshu"]])citiesRef.document("BJ").setData(["name":"Beijing","country":"China","capital":true,"population":21500000,"regions":["jingjinji","hebei"]])
Objective-C
FIRCollectionReference*citiesRef=[self.dbcollectionWithPath:@"cities"];[[citiesRefdocumentWithPath:@"SF"]setData:@{@"name":@"San Francisco",@"state":@"CA",@"country":@"USA",@"capital":@(NO),@"population":@860000,@"regions":@[@"west_coast",@"norcal"]}];[[citiesRefdocumentWithPath:@"LA"]setData:@{@"name":@"Los Angeles",@"state":@"CA",@"country":@"USA",@"capital":@(NO),@"population":@3900000,@"regions":@[@"west_coast",@"socal"]}];[[citiesRefdocumentWithPath:@"DC"]setData:@{@"name":@"Washington D.C.",@"country":@"USA",@"capital":@(YES),@"population":@680000,@"regions":@[@"east_coast"]}];[[citiesRefdocumentWithPath:@"TOK"]setData:@{@"name":@"Tokyo",@"country":@"Japan",@"capital":@(YES),@"population":@9000000,@"regions":@[@"kanto",@"honshu"]}];[[citiesRefdocumentWithPath:@"BJ"]setData:@{@"name":@"Beijing",@"country":@"China",@"capital":@(YES),@"population":@21500000,@"regions":@[@"jingjinji",@"hebei"]}];
Kotlin
valcities=db.collection("cities")valdata1=hashMapOf("name"to"San Francisco","state"to"CA","country"to"USA","capital"tofalse,"population"to860000,"regions"tolistOf("west_coast","norcal"),)cities.document("SF").set(data1)valdata2=hashMapOf("name"to"Los Angeles","state"to"CA","country"to"USA","capital"tofalse,"population"to3900000,"regions"tolistOf("west_coast","socal"),)cities.document("LA").set(data2)valdata3=hashMapOf("name"to"Washington D.C.","state"tonull,"country"to"USA","capital"totrue,"population"to680000,"regions"tolistOf("east_coast"),)cities.document("DC").set(data3)valdata4=hashMapOf("name"to"Tokyo","state"tonull,"country"to"Japan","capital"totrue,"population"to9000000,"regions"tolistOf("kanto","honshu"),)cities.document("TOK").set(data4)valdata5=hashMapOf("name"to"Beijing","state"tonull,"country"to"China","capital"totrue,"population"to21500000,"regions"tolistOf("jingjinji","hebei"),)cities.document("BJ").set(data5)
Java
CollectionReferencecities=db.collection("cities");Map<String,Object>data1=newHashMap<>();data1.put("name","San Francisco");data1.put("state","CA");data1.put("country","USA");data1.put("capital",false);data1.put("population",860000);data1.put("regions",Arrays.asList("west_coast","norcal"));cities.document("SF").set(data1);Map<String,Object>data2=newHashMap<>();data2.put("name","Los Angeles");data2.put("state","CA");data2.put("country","USA");data2.put("capital",false);data2.put("population",3900000);data2.put("regions",Arrays.asList("west_coast","socal"));cities.document("LA").set(data2);Map<String,Object>data3=newHashMap<>();data3.put("name","Washington D.C.");data3.put("state",null);data3.put("country","USA");data3.put("capital",true);data3.put("population",680000);data3.put("regions",Arrays.asList("east_coast"));cities.document("DC").set(data3);Map<String,Object>data4=newHashMap<>();data4.put("name","Tokyo");data4.put("state",null);data4.put("country","Japan");data4.put("capital",true);data4.put("population",9000000);data4.put("regions",Arrays.asList("kanto","honshu"));cities.document("TOK").set(data4);Map<String,Object>data5=newHashMap<>();data5.put("name","Beijing");data5.put("state",null);data5.put("country","China");data5.put("capital",true);data5.put("population",21500000);data5.put("regions",Arrays.asList("jingjinji","hebei"));cities.document("BJ").set(data5);
Dart
finalcities=db.collection("cities");finaldata1=<String,dynamic>{"name":"San Francisco","state":"CA","country":"USA","capital":false,"population":860000,"regions":["west_coast","norcal"]};cities.doc("SF").set(data1);finaldata2=<String,dynamic>{"name":"Los Angeles","state":"CA","country":"USA","capital":false,"population":3900000,"regions":["west_coast","socal"],};cities.doc("LA").set(data2);finaldata3=<String,dynamic>{"name":"Washington D.C.","state":null,"country":"USA","capital":true,"population":680000,"regions":["east_coast"]};cities.doc("DC").set(data3);finaldata4=<String,dynamic>{"name":"Tokyo","state":null,"country":"Japan","capital":true,"population":9000000,"regions":["kanto","honshu"]};cities.doc("TOK").set(data4);finaldata5=<String,dynamic>{"name":"Beijing","state":null,"country":"China","capital":true,"population":21500000,"regions":["jingjinji","hebei"],};cities.doc("BJ").set(data5);
Java
CollectionReferencecities=db.collection("cities");List<ApiFuture<WriteResult>>futures=newArrayList<>();futures.add(cities.document("SF").set(newCity("San Francisco","CA","USA",false,860000L,Arrays.asList("west_coast","norcal"))));futures.add(cities.document("LA").set(newCity("Los Angeles","CA","USA",false,3900000L,Arrays.asList("west_coast","socal"))));futures.add(cities.document("DC").set(newCity("Washington D.C.",null,"USA",true,680000L,Arrays.asList("east_coast"))));futures.add(cities.document("TOK").set(newCity("Tokyo",null,"Japan",true,9000000L,Arrays.asList("kanto","honshu"))));futures.add(cities.document("BJ").set(newCity("Beijing",null,"China",true,21500000L,Arrays.asList("jingjinji","hebei"))));// (optional) block on operationApiFutures.allAsList(futures).get();Python
classCity:def__init__(self,name,state,country,capital=False,population=0,regions=[]):self.name=nameself.state=stateself.country=countryself.capital=capitalself.population=populationself.regions=regions@staticmethoddeffrom_dict(source):# ...defto_dict(self):# ...def__repr__(self):returnf"City(\ name={self.name},\ country={self.country},\ population={self.population},\ capital={self.capital},\ regions={self.regions}\ )"
cities_ref=db.collection("cities")cities_ref.document("BJ").set(City("Beijing",None,"China",True,21500000,["hebei"]).to_dict())cities_ref.document("SF").set(City("San Francisco","CA","USA",False,860000,["west_coast","norcal"]).to_dict())cities_ref.document("LA").set(City("Los Angeles","CA","USA",False,3900000,["west_coast","socal"]).to_dict())cities_ref.document("DC").set(City("Washington D.C.",None,"USA",True,680000,["east_coast"]).to_dict())cities_ref.document("TOK").set(City("Tokyo",None,"Japan",True,9000000,["kanto","honshu"]).to_dict())
Python
cities_ref=db.collection("cities")awaitcities_ref.document("BJ").set(City("Beijing",None,"China",True,21500000,["hebei"]).to_dict())awaitcities_ref.document("SF").set(City("San Francisco","CA","USA",False,860000,["west_coast","norcal"]).to_dict())awaitcities_ref.document("LA").set(City("Los Angeles","CA","USA",False,3900000,["west_coast","socal"]).to_dict())awaitcities_ref.document("DC").set(City("Washington D.C.",None,"USA",True,680000,["east_coast"]).to_dict())awaitcities_ref.document("TOK").set(City("Tokyo",None,"Japan",True,9000000,["kanto","honshu"]).to_dict())C++
CollectionReferencecities=db->Collection("cities");cities.Document("SF").Set({{"name",FieldValue::String("San Francisco")},{"state",FieldValue::String("CA")},{"country",FieldValue::String("USA")},{"capital",FieldValue::Boolean(false)},{"population",FieldValue::Integer(860000)},{"regions",FieldValue::Array({FieldValue::String("west_coast"),FieldValue::String("norcal")})},});cities.Document("LA").Set({{"name",FieldValue::String("Los Angeles")},{"state",FieldValue::String("CA")},{"country",FieldValue::String("USA")},{"capital",FieldValue::Boolean(false)},{"population",FieldValue::Integer(3900000)},{"regions",FieldValue::Array({FieldValue::String("west_coast"),FieldValue::String("socal")})},});cities.Document("DC").Set({{"name",FieldValue::String("Washington D.C.")},{"state",FieldValue::Null()},{"country",FieldValue::String("USA")},{"capital",FieldValue::Boolean(true)},{"population",FieldValue::Integer(680000)},{"regions",FieldValue::Array({FieldValue::String("east_coast")})},});cities.Document("TOK").Set({{"name",FieldValue::String("Tokyo")},{"state",FieldValue::Null()},{"country",FieldValue::String("Japan")},{"capital",FieldValue::Boolean(true)},{"population",FieldValue::Integer(9000000)},{"regions",FieldValue::Array({FieldValue::String("kanto"),FieldValue::String("honshu")})},});cities.Document("BJ").Set({{"name",FieldValue::String("Beijing")},{"state",FieldValue::Null()},{"country",FieldValue::String("China")},{"capital",FieldValue::Boolean(true)},{"population",FieldValue::Integer(21500000)},{"regions",FieldValue::Array({FieldValue::String("jingjinji"),FieldValue::String("hebei")})},});
Node.js
constcitiesRef=db.collection('cities');awaitcitiesRef.doc('SF').set({name:'San Francisco',state:'CA',country:'USA',capital:false,population:860000});awaitcitiesRef.doc('LA').set({name:'Los Angeles',state:'CA',country:'USA',capital:false,population:3900000});awaitcitiesRef.doc('DC').set({name:'Washington, D.C.',state:null,country:'USA',capital:true,population:680000});awaitcitiesRef.doc('TOK').set({name:'Tokyo',state:null,country:'Japan',capital:true,population:9000000});awaitcitiesRef.doc('BJ').set({name:'Beijing',state:null,country:'China',capital:true,population:21500000});Go
import("context""cloud.google.com/go/firestore")funcprepareRetrieve(ctxcontext.Context,client*firestore.Client)error{cities:=[]struct{idstringcCity}{{id:"SF",c:City{Name:"San Francisco",State:"CA",Country:"USA",Capital:false,Population:860000}},{id:"LA",c:City{Name:"Los Angeles",State:"CA",Country:"USA",Capital:false,Population:3900000}},{id:"DC",c:City{Name:"Washington D.C.",Country:"USA",Capital:true,Population:680000}},{id:"TOK",c:City{Name:"Tokyo",Country:"Japan",Capital:true,Population:9000000}},{id:"BJ",c:City{Name:"Beijing",Country:"China",Capital:true,Population:21500000}},}for_,c:=rangecities{_,err:=client.Collection("cities").Doc(c.id).Set(ctx,c.c)iferr!=nil{returnerr}}returnnil}PHP
PHP
For more on installing and creating aCloud Firestore client, refer toCloud Firestore Client Libraries.
$citiesRef = $db->collection('samples/php/cities');$citiesRef->document('SF')->set([ 'name' => 'San Francisco', 'state' => 'CA', 'country' => 'USA', 'capital' => false, 'population' => 860000, 'density' => 18000,]);$citiesRef->document('LA')->set([ 'name' => 'Los Angeles', 'state' => 'CA', 'country' => 'USA', 'capital' => false, 'population' => 3900000, 'density' => 8000,]);$citiesRef->document('DC')->set([ 'name' => 'Washington D.C.', 'state' => null, 'country' => 'USA', 'capital' => true, 'population' => 680000, 'density' => 11000,]);$citiesRef->document('TOK')->set([ 'name' => 'Tokyo', 'state' => null, 'country' => 'Japan', 'capital' => true, 'population' => 9000000, 'density' => 16000,]);$citiesRef->document('BJ')->set([ 'name' => 'Beijing', 'state' => null, 'country' => 'China', 'capital' => true, 'population' => 21500000, 'density' => 3500,]);printf('Added example cities data to the cities collection.' . PHP_EOL);Unity
CollectionReferencecitiesRef=db.Collection("cities");citiesRef.Document("SF").SetAsync(newDictionary<string,object>(){{"Name","San Francisco"},{"State","CA"},{"Country","USA"},{"Capital",false},{"Population",860000}}).ContinueWithOnMainThread(task=>citiesRef.Document("LA").SetAsync(newDictionary<string,object>(){{"Name","Los Angeles"},{"State","CA"},{"Country","USA"},{"Capital",false},{"Population",3900000}})).ContinueWithOnMainThread(task=>citiesRef.Document("DC").SetAsync(newDictionary<string,object>(){{"Name","Washington D.C."},{"State",null},{"Country","USA"},{"Capital",true},{"Population",680000}})).ContinueWithOnMainThread(task=>citiesRef.Document("TOK").SetAsync(newDictionary<string,object>(){{"Name","Tokyo"},{"State",null},{"Country","Japan"},{"Capital",true},{"Population",9000000}})).ContinueWithOnMainThread(task=>citiesRef.Document("BJ").SetAsync(newDictionary<string,object>(){{"Name","Beijing"},{"State",null},{"Country","China"},{"Capital",true},{"Population",21500000}}));
C#
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.");Ruby
cities_ref=firestore.colcollection_pathcities_ref.doc("SF").set({name:"San Francisco",state:"CA",country:"USA",capital:false,population:860_000})cities_ref.doc("LA").set({name:"Los Angeles",state:"CA",country:"USA",capital:false,population:3_900_000})cities_ref.doc("DC").set({name:"Washington D.C.",state:nil,country:"USA",capital:true,population:680_000})cities_ref.doc("TOK").set({name:"Tokyo",state:nil,country:"Japan",capital:true,population:9_000_000})cities_ref.doc("BJ").set({name:"Beijing",state:nil,country:"China",capital:true,population:21_500_000})Get a document
The following example shows how to retrieve the contents of a single documentusingget():
Web
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!");}
Web
Learn more about the tree-shakeable modular Web API and its advantages over the namespaced API.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);});
Swift
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)")}
Objective-C
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");}}];
Kotlin
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)}
Java
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());}}});
Dart
finaldocRef=db.collection("cities").doc("SF");docRef.get().then((DocumentSnapshotdoc){finaldata=doc.data()asMap<String,dynamic>;// ...},onError:(e)=>print("Error getting document:$e"),);
Java
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!");}Python
doc_ref=db.collection("cities").document("SF")doc=doc_ref.get()ifdoc.exists:print(f"Document data:{doc.to_dict()}")else:print("No such document!")Python
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!")C++
DocumentReferencedoc_ref=db->Collection("cities").Document("SF");doc_ref.Get().OnCompletion([](constFuture<DocumentSnapshot>&future){if(future.error()==Error::kErrorOk){constDocumentSnapshot&document=*future.result();if(document.exists()){std::cout <<"DocumentSnapshot id: " <<document.id() <<std::endl;}else{std::cout <<"no such document" <<std::endl;}}else{std::cout <<"Get failed with: " <<future.error_message() <<std::endl;}});
Node.js
constcityRef=db.collection('cities').doc('SF');constdoc=awaitcityRef.get();if(!doc.exists){console.log('No such document!');}else{console.log('Document data:',doc.data());}Go
import("context""fmt""cloud.google.com/go/firestore")funcdocAsMap(ctxcontext.Context,client*firestore.Client)(map[string]interface{},error){dsnap,err:=client.Collection("cities").Doc("SF").Get(ctx)iferr!=nil{returnnil,err}m:=dsnap.Data()fmt.Printf("Document data: %#v\n",m)returnm,nil}PHP
PHP
For more on installing and creating aCloud Firestore client, refer toCloud Firestore Client Libraries.
$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);}Ruby
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!"enddocRef, theresultingdocument will be empty and callingexists on it will returnfalse.Source Options
For platforms with offline support, you can set thesource option to controlhow aget call uses the offline cache.
By default, aget call will attempt to fetch the latest document snapshot fromyour database. On platforms with offline support, the client library will usethe offline cache if the network is unavailable or if the request times out.
You can specify thesource option in aget() call to changethe default behavior. You can fetch from only the database and ignorethe offline cache, or you can fetch from only the offline cache. For example:
Web
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);}
Web
Learn more about the tree-shakeable modular Web API and its advantages over the namespaced API.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);});
Swift
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)")}
Objective-C
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);}}];
Kotlin
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)}}
Java
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());}}});
Dart
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"),);
Java
Not supported in the Java SDK.
Python
Not supported in the Python SDK.
C++
DocumentReferencedoc_ref=db->Collection("cities").Document("SF");Sourcesource=Source::kCache;doc_ref.Get(source).OnCompletion([](constFuture<DocumentSnapshot>&future){if(future.error()==Error::kErrorOk){constDocumentSnapshot&document=*future.result();if(document.exists()){std::cout <<"Cached document id: " <<document.id() <<std::endl;}else{}}else{std::cout <<"Cached get failed: " <<future.error_message() <<std::endl;}});
Node.js
Not supported in the Node.js SDK.
Go
Not supported in the Go SDK.
PHP
Not supported in the PHP SDK.
Unity
Not supported in the Unity SDK.
C#
Not supported in the C# SDK.
Ruby
Not supported in the Ruby SDK.
Custom objects
The previous example retrieved the contents of thedocument as a map, but in some languages it's often more convenient to use acustom object type. InAdd Data, you defined aCity classthat 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
Learn more about the tree-shakeable Web v9 modular SDK andupgrade from version 8.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);}};
To use custom objects, you must define aFirestoreDataConverterfunction for your class. For example:
Web
Learn more about the tree-shakeable Web v9 modular SDK andupgrade from version 8.classCity{constructor(name,state,country){this.name=name;this.state=state;this.country=country;}toString(){returnthis.name+', '+this.state+', '+this.country;}}// Firestore data convertervarcityConverter={toFirestore:function(city){return{name:city.name,state:city.state,country:city.country};},fromFirestore:function(snapshot,options){constdata=snapshot.data(options);returnnewCity(data.name,data.state,data.country);}};
Call your data converter with your read operations. After conversion, you canaccess custom object methods:
Web
Learn more about the tree-shakeable Web v9 modular SDK andupgrade from version 8.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 canaccess custom object methods:
Web
Learn more about the tree-shakeable Web v9 modular SDK andupgrade from 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);});
Swift
To support automatic type serialization in Swift, your type must conform to theCodable protocol.
letdocRef=db.collection("cities").document("BJ")do{letcity=tryawaitdocRef.getDocument(as:City.self)print("City:\(city)")}catch{print("Error decoding city:\(error)")}
Objective-C
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");}}];
Kotlin
valdocRef=db.collection("cities").document("BJ")docRef.get().addOnSuccessListener{documentSnapshot->valcity=documentSnapshot.toObject<City>()}
Java
Important: Each custom class must have a public constructor that takes noarguments. In addition, the class must include a public getter for eachproperty.
DocumentReferencedocRef=db.collection("cities").document("BJ");docRef.get().addOnSuccessListener(newOnSuccessListener<DocumentSnapshot>(){@OverridepublicvoidonSuccess(DocumentSnapshotdocumentSnapshot){Citycity=documentSnapshot.toObject(City.class);}});
Dart
To use custom objects, you must define Firestore data conversion functions for your class. For example:
classCity{finalString?name;finalString?state;finalString?country;finalbool?capital;finalint?population;finalList<String>?regions;City({this.name,this.state,this.country,this.capital,this.population,this.regions,});factoryCity.fromFirestore(DocumentSnapshot<Map<String,dynamic>>snapshot,SnapshotOptions?options,){finaldata=snapshot.data();returnCity(name:data?['name'],state:data?['state'],country:data?['country'],capital:data?['capital'],population:data?['population'],regions:data?['regions']isIterable?List.from(data?['regions']):null,);}Map<String,dynamic>toFirestore(){return{if(name!=null)"name":name,if(state!=null)"state":state,if(country!=null)"country":country,if(capital!=null)"capital":capital,if(population!=null)"population":population,if(regions!=null)"regions":regions,};}}
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.");}
Java
Each custom class must have a public constructor that takes noarguments. In addition, the class must include a public getter for eachproperty.
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!");}Python
doc_ref=db.collection("cities").document("BJ")doc=doc_ref.get()city=City.from_dict(doc.to_dict())print(city)Python
doc_ref=db.collection("cities").document("BJ")doc=awaitdoc_ref.get()city=City.from_dict(doc.to_dict())print(city)C++
// This is not yet supported.Node.js
Node.js uses JavaScript objects.
Go
import("context""fmt""cloud.google.com/go/firestore")funcdocAsEntity(ctxcontext.Context,client*firestore.Client)(*City,error){dsnap,err:=client.Collection("cities").Doc("BJ").Get(ctx)iferr!=nil{returnnil,err}varcCitydsnap.DataTo(&c)fmt.Printf("Document data: %#v\n",c)return&c,nil}PHP
PHP
For more on installing and creating aCloud Firestore client, refer toCloud Firestore Client Libraries.
$docRef = $db->collection('samples/php/cities')->document('SF');$snapshot = $docRef->snapshot();$city = City::fromArray($snapshot->data());if ($snapshot->exists()) { printf('Document data:' . PHP_EOL); print((string) $city);} else { printf('Document %s does not exist!' . PHP_EOL, $snapshot->id());}Unity
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);}Ruby
Not applicable for Ruby.
Get multiple documents from a collection
You can also retrieve multiple documents with one request by querying documentsin a collection. For example, you can usewhere() to query for all of thedocuments that meet a certain condition, then useget() to retrieve theresults:
Web
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());});
Web
Learn more about the tree-shakeable modular Web API and its advantages over the namespaced API.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);});
Swift
do{letquerySnapshot=tryawaitdb.collection("cities").whereField("capital",isEqualTo:true).getDocuments()fordocumentinquerySnapshot.documents{print("\(document.documentID) =>\(document.data())")}}catch{print("Error getting documents:\(error)")}
Objective-C
[[[self.dbcollectionWithPath:@"cities"]queryWhereField:@"capital"isEqualTo:@(YES)]getDocumentsWithCompletion:^(FIRQuerySnapshot*snapshot,NSError*error){if(error!=nil){NSLog(@"Error getting documents: %@",error);}else{for(FIRDocumentSnapshot*documentinsnapshot.documents){NSLog(@"%@ => %@",document.documentID,document.data);}}}];
Kotlin
db.collection("cities").whereEqualTo("capital",true).get().addOnSuccessListener{documents->for(documentindocuments){Log.d(TAG,"${document.id} =>${document.data}")}}.addOnFailureListener{exception->Log.w(TAG,"Error getting documents: ",exception)}
Java
db.collection("cities").whereEqualTo("capital",true).get().addOnCompleteListener(newOnCompleteListener<QuerySnapshot>(){@OverridepublicvoidonComplete(@NonNullTask<QuerySnapshot>task){if(task.isSuccessful()){for(QueryDocumentSnapshotdocument:task.getResult()){Log.d(TAG,document.getId()+" => "+document.getData());}}else{Log.d(TAG,"Error getting documents: ",task.getException());}}});
Dart
db.collection("cities").where("capital",isEqualTo:true).get().then((querySnapshot){print("Successfully completed");for(vardocSnapshotinquerySnapshot.docs){print('${docSnapshot.id} =>${docSnapshot.data()}');}},onError:(e)=>print("Error completing:$e"),);
Java
// asynchronously retrieve multiple documentsApiFuture<QuerySnapshot>future=db.collection("cities").whereEqualTo("capital",true).get();// future.get() blocks on responseList<QueryDocumentSnapshot>documents=future.get().getDocuments();for(DocumentSnapshotdocument:documents){System.out.println(document.getId()+" => "+document.toObject(City.class));}Python
# 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()}")Python
# 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()}")C++
db->Collection("cities").WhereEqualTo("capital",FieldValue::Boolean(true)).Get().OnCompletion([](constFuture<QuerySnapshot>&future){if(future.error()==Error::kErrorOk){for(constDocumentSnapshot&document:future.result()->documents()){std::cout <<document <<std::endl;}}else{std::cout <<"Error getting documents: " <<future.error_message() <<std::endl;}});
Node.js
constcitiesRef=db.collection('cities');constsnapshot=awaitcitiesRef.where('capital','==',true).get();if(snapshot.empty){console.log('No matching documents.');return;}snapshot.forEach(doc=>{console.log(doc.id,'=>',doc.data());});Go
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}PHP
PHP
For more on installing and creating aCloud Firestore client, refer toCloud Firestore Client Libraries.
$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("");}Ruby
cities_ref=firestore.colcollection_pathquery=cities_ref.where"capital","=",truequery.getdo|city|puts"#{city.document_id} data:#{city.data}."endBy default,Cloud Firestore retrieves all documents that satisfy thequery in ascending order by document ID, but you canorder and limit the datareturned.
Get all documents in a collection
In addition, you can retrieveall documents in a collection by omitting thewhere() filter entirely:
Web
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());});
Web
Learn more about the tree-shakeable modular Web API and its advantages over the namespaced API.db.collection("cities").get().then((querySnapshot)=>{querySnapshot.forEach((doc)=>{// doc.data() is never undefined for query doc snapshotsconsole.log(doc.id," => ",doc.data());});});
Swift
do{letquerySnapshot=tryawaitdb.collection("cities").getDocuments()fordocumentinquerySnapshot.documents{print("\(document.documentID) =>\(document.data())")}}catch{print("Error getting documents:\(error)")}
Objective-C
[[self.dbcollectionWithPath:@"cities"]getDocumentsWithCompletion:^(FIRQuerySnapshot*snapshot,NSError*error){if(error!=nil){NSLog(@"Error getting documents: %@",error);}else{for(FIRDocumentSnapshot*documentinsnapshot.documents){NSLog(@"%@ => %@",document.documentID,document.data);}}}];
Kotlin
db.collection("cities").get().addOnSuccessListener{result->for(documentinresult){Log.d(TAG,"${document.id} =>${document.data}")}}.addOnFailureListener{exception->Log.d(TAG,"Error getting documents: ",exception)}
Java
db.collection("cities").get().addOnCompleteListener(newOnCompleteListener<QuerySnapshot>(){@OverridepublicvoidonComplete(@NonNullTask<QuerySnapshot>task){if(task.isSuccessful()){for(QueryDocumentSnapshotdocument:task.getResult()){Log.d(TAG,document.getId()+" => "+document.getData());}}else{Log.d(TAG,"Error getting documents: ",task.getException());}}});
Dart
db.collection("cities").get().then((querySnapshot){print("Successfully completed");for(vardocSnapshotinquerySnapshot.docs){print('${docSnapshot.id} =>${docSnapshot.data()}');}},onError:(e)=>print("Error completing:$e"),);
Java
// asynchronously retrieve all documentsApiFuture<QuerySnapshot>future=db.collection("cities").get();// future.get() blocks on responseList<QueryDocumentSnapshot>documents=future.get().getDocuments();for(QueryDocumentSnapshotdocument:documents){System.out.println(document.getId()+" => "+document.toObject(City.class));}Python
docs=db.collection("cities").stream()fordocindocs:print(f"{doc.id} =>{doc.to_dict()}")Python
docs=db.collection("cities").stream()asyncfordocindocs:print(f"{doc.id} =>{doc.to_dict()}")C++
db->Collection("cities").Get().OnCompletion([](constFuture<QuerySnapshot>&future){if(future.error()==Error::kErrorOk){for(constDocumentSnapshot&document:future.result()->documents()){std::cout <<document <<std::endl;}}else{std::cout <<"Error getting documents: " <<future.error_message() <<std::endl;}});
Node.js
constcitiesRef=db.collection('cities');constsnapshot=awaitcitiesRef.get();snapshot.forEach(doc=>{console.log(doc.id,'=>',doc.data());});Go
import("context""fmt""cloud.google.com/go/firestore""google.golang.org/api/iterator")funcallDocs(ctxcontext.Context,client*firestore.Client)error{fmt.Println("All cities:")iter:=client.Collection("cities").Documents(ctx)deferiter.Stop()for{doc,err:=iter.Next()iferr==iterator.Done{break}iferr!=nil{returnerr}fmt.Println(doc.Data())}returnnil}PHP
PHP
For more on installing and creating aCloud Firestore client, refer toCloud Firestore Client Libraries.
$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("");}Ruby
cities_ref=firestore.colcollection_pathcities_ref.getdo|city|puts"#{city.document_id} data:#{city.data}."endGet all documents in a subcollection
To retrieve all the documents from a subcollection, create a reference with thecomplete path to that subcollection:
Web
Learn more about the tree-shakeable Web v9 modular SDK andupgrade from version 8.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());});
Web
// Snippet not available
Swift
do{letquerySnapshot=tryawaitdb.collection("cities/SF/landmarks").getDocuments()fordocumentinquerySnapshot.documents{print("\(document.documentID) =>\(document.data())")}}catch{print("Error getting documents:\(error)")}
Objective-C
[[self.dbcollectionWithPath:@"cities/SF/landmarks"]getDocumentsWithCompletion:^(FIRQuerySnapshot*snapshot,NSError*error){if(error!=nil){NSLog(@"Error getting documents: %@",error);}else{for(FIRDocumentSnapshot*documentinsnapshot.documents){NSLog(@"%@ => %@",document.documentID,document.data);}}}];
Kotlin
db.collection("cities").document("SF").collection("landmarks").get().addOnSuccessListener{result->for(documentinresult){Log.d(TAG,"${document.id} =>${document.data}")}}.addOnFailureListener{exception->Log.d(TAG,"Error getting documents: ",exception)}
Java
db.collection("cities").document("SF").collection("landmarks").get().addOnCompleteListener(newOnCompleteListener<QuerySnapshot>(){@OverridepublicvoidonComplete(@NonNullTask<QuerySnapshot>task){if(task.isSuccessful()){for(QueryDocumentSnapshotdocument:task.getResult()){Log.d(TAG,document.getId()+" => "+document.getData());}}else{Log.d(TAG,"Error getting documents: ",task.getException());}}});
Dart
db.collection("cities").doc("SF").collection("landmarks").get().then((querySnapshot){print("Successfully completed");for(vardocSnapshotinquerySnapshot.docs){print('${docSnapshot.id}=>${docSnapshot.data()}');}},onError:(e)=>print("Error completing: $e"),);
Java
// Snippet not available
Python
// Snippet not available
Python
// Snippet not available
C++
// Snippet not available
Node.js
// Snippet not available
Go
// Snippet not available
PHP
// Snippet not available
Unity
// Snippet not available
C#
// Snippet not available
Ruby
// Snippet not available
Get multiple documents from a collection group
A collection group consists of all collections with the same ID. For example, ifeach document in yourcities collection has a subcollection calledlandmarks, all of thelandmarks subcollections belong to the same collectiongroup. By default, queries retrieve results from a single collection in yourdatabase.Use a collection group query to retrieve results from a collectiongroup instead of from a single collection.
List subcollections of a document
ThelistCollections() method of theCloud Firestore server client librarieslists 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 tasksin trusted server environments. If you find that you need this capabilityin the mobile/web client libraries, consider restructuring your data so thatsubcollection 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
Not available in the Android client library.
Java
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());}Python
city_ref=db.collection("cities").document("SF")collections=city_ref.collections()forcollectionincollections:fordocincollection.stream():print(f"{doc.id} =>{doc.to_dict()}")Python
collections=db.collection("cities").document("SF").collections()asyncforcollectionincollections:asyncfordocincollection.stream():print(f"{doc.id} =>{doc.to_dict()}")C++
Not available in the C++ client library.
Node.js
constsfRef=db.collection('cities').doc('SF');constcollections=awaitsfRef.listCollections();collections.forEach(collection=>{console.log('Found subcollection with id:',collection.id);});Go
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}PHP
PHP
For more on installing and creating aCloud Firestore client, refer toCloud Firestore Client Libraries.
$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);}Ruby
city_ref=firestore.doc"#{collection_path}/SF"city_ref.colsdo|col|putscol.collection_idendLearn more about differenttypes of queries.
For more information on error codes and how to resolve latency issues when getting data check out thetroubleshooting page.
Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2025-12-17 UTC.