Stay organized with collectionsSave and categorize content based on your preferences.
This quickstart shows you how to set upCloud Firestore, add data, then view
the data you just added in the Firebase console.
Create aCloud Firestoredatabase
If you haven't already, create a Firebase project: In theFirebaseconsole, clickAdd project,
then follow the on-screen instructions to create a Firebase project or to
add Firebase services to an existingGoogle Cloudproject.
Open your project in theFirebaseconsole. In the left panel, expandBuildand then selectFirestore database.
If you aren't able to select a location, then your project's"location for defaultGoogle Cloudresources"has already been set. Some of your project's resources (like the defaultCloud Firestoreinstance) share a common location dependency, and
their location can be set either during project creation or when setting up
another service that shares this location dependency.
Select a starting mode for yourCloud FirestoreSecurity Rules:
Test mode
Good for getting started with the mobile and web client libraries,
but allows anyone to read and overwrite your data. After testing,make
sure to review theSecure your datasection.
To get started with the web, Apple platforms, or Android SDK, select test mode.
Production mode
Denies all reads and writes from mobile and web clients.
Your authenticated application servers (C#, Go, Java, Node.js, PHP,
Python, or Ruby) can still access your database.
To get started with the C#, Go, Java, Node.js, PHP, Python, or Ruby
server client library, select production mode.
Your initial set ofCloud FirestoreSecurity Ruleswill apply to your defaultCloud Firestoredatabase. If you create multiple databases for your
project, you can deployCloud FirestoreSecurity Rulesfor each database.
ClickCreate.
When you enableCloud Firestore, it also enables the API in theCloud API Manager.
Set up your development environment
Add the required dependencies and client libraries to your app.
Using theFirebase Android BoM,
declare the dependency for theCloud Firestorelibrary for Android in
yourmodule (app-level) Gradle file(usuallyapp/build.gradle.ktsorapp/build.gradle).
dependencies{// Import the BoM for the Firebase platformimplementation(platform("com.google.firebase:firebase-bom:34.2.0"))// Declare the dependency for theCloud Firestorelibrary// When using the BoM, you don't specify versions in Firebase library dependenciesimplementation("com.google.firebase:firebase-firestore")}
By using theFirebase Android BoM,
your app will always use compatible versions of the Firebase Android
libraries.
If you choose not to use theFirebase BoM, you must specify each
Firebase library version in its dependency line.
Note that if you usemultipleFirebase libraries in
your app, we highly recommend using theBoMto manage library
versions, which ensures that all versions are compatible.
dependencies{// Declare the dependency for theCloud Firestorelibrary// When NOT using the BoM, you must specify versions in Firebase library dependenciesimplementation("com.google.firebase:firebase-firestore:26.0.0")}
Looking for a Kotlin-specific library module?Starting with theOctober 2023 release,
both Kotlin and Java developers can depend on the main library module
(for details, see theFAQ about this initiative).
From the root of your Flutter project, run the following command to
install the plugin:
flutter pub add cloud_firestore
Once complete, rebuild your Flutter application:
flutter run
Optional:Improve iOS & macOS build times by including the
pre-compiled framework.
Currently, the Firestore SDK for iOS depends on code that can take
upwards of 5 minutes to build in Xcode. To reduce build times
significantly, you can use a pre-compiled version by adding this line to
thetarget 'Runner' doblock in your Podfile:
target 'Runner' do
use_frameworks!
use_modular_headers!pod 'FirebaseFirestore',
:git => 'https://github.com/invertase/firestore-ios-sdk-frameworks.git',
:tag => 'IOS_SDK_VERSION'flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))
target 'RunnerTests' do
inherit! :search_paths
end
end
ReplaceIOS_SDK_VERSIONwith the version of the Firebase iOS
SDK specified infirebase_core'sfirebase_sdk_version.rbfile. If you're not using the latest version offirebase_core, look for this file in your local Pub package
cache (usually~/.pub-cache).
Additionally, ensure that you have upgraded CocoaPods to 1.9.1 or
higher:
Binary dependencies.Similarly, the recommended way to get
the binary dependencies is to add the following to yourCMakeLists.txtfile:
add_subdirectory(${FIREBASE_CPP_SDK_DIR}bin/EXCLUDE_FROM_ALL)set(firebase_libsfirebase_authfirebase_firestorefirebase_app)# Replace the target name below with the actual name of your target,# for example, "native-lib".target_link_libraries(${YOUR_TARGET_NAME_HERE}"${firebase_libs}")
To authenticate from your development environment, set theGOOGLE_APPLICATION_CREDENTIALSenvironment variable to point to a JSON service account key file. You can create a key file
on theAPI Console Credentials page.
In your production environment, you do not need to authenticate if you run your application
on App Engine or Compute Engine, using the same project that you use forCloud Firestore. Otherwise,set up a service account.
Install and enable thegRPC extensionfor PHP, which you will need to use the client library.
To authenticate from your development environment, set theGOOGLE_APPLICATION_CREDENTIALSenvironment variable to point to a JSON service account key file. You can create a key file
on theAPI Console Credentials page.
In your production environment, you do not need to authenticate if you run your application
on App Engine or Compute Engine, using the same project that you use forCloud Firestore. Otherwise,set up a service account.
Add the Cloud Firestore C# library to your app in your.csprojfile:
To authenticate from your development environment, set theGOOGLE_APPLICATION_CREDENTIALSenvironment variable to point to a JSON service account key file. You can create a key file
on theAPI Console Credentials page.
In your production environment, you do not need to authenticate if you run your application
on App Engine or Compute Engine, using the same project that you use forCloud Firestore. Otherwise,set up a service account.
Add the Cloud Firestore Ruby library to your app in yourGemfile:
gem"google-cloud-firestore"
Install dependencies from yourGemfileusing:
bundleinstall
(Optional) Prototype and test withFirebase Local Emulator Suite
For mobile developers, before talking about how your app writes to and reads
fromCloud Firestore, let's introduce a set of tools you can use to
prototype and testCloud Firestorefunctionality:Firebase Local Emulator Suite. If you're trying out different data models,
optimizing your security rules, or working to find the most cost-effective way
to interact with the back-end, being able to work locally without deploying
live services can be a great idea.
ACloud Firestoreemulator is part of theLocal Emulator Suite, which
enables your app to interact with your emulated database content and config, as
well as optionally your emulated project resources (functions, other databases,
and security rules).
Using theCloud Firestoreemulator involves just a few steps:
Adding a line of code to your app's test config to connect to the emulator.
From the root of your local project directory, runningfirebase emulators:start.
Making calls from your app's prototype code using aCloud Firestoreplatform
SDK as usual.
TheCloud FirestoreSDK is initialized in different ways depending on
your environment. Below are the most common methods. For a complete reference,
seeInitialize
the Admin SDK.
Initialize onGoogle Cloud
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();
Initialize on your own server
To use the Firebase Admin SDK on your own server, use aservice account.
Go toIAM & admin > Service accountsin 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 FirestoreSDK is initialized in different ways depending on
your environment. Below are the most common methods. For a complete reference,
seeInitialize
the Admin SDK.
Initialize onGoogle Cloud
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 accountsin 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()
TheCloud FirestoreSDK is initialized in different ways depending on
your environment. Below are the most common methods. For a complete reference,
seeInitialize
the Admin SDK.
Initialize onGoogle Cloud
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 accountsin 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()
TheCloud FirestoreSDK is initialized in different ways depending on
your environment. Below are the most common methods. For a complete reference,
seeInitialize
the Admin SDK.
To use the Firebase Admin SDK on your own server (or any other Node.js environment),
use aservice account.
Go toIAM & admin > Service accountsin the Google Cloud console. Generate a new private key and save the JSON file. Then use the file to initialize the SDK:
TheCloud FirestoreSDK is initialized in different ways depending on
your environment. Below are the most common methods. For a complete reference,
seeInitialize
the Admin SDK.
Initialize onGoogle Cloud
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()
Initialize on your own server
To use the Firebase Admin SDK on your own server, use aservice account.
Go toIAM & admin > Service accountsin 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()
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);}}
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."
Cloud Firestorestores data in Documents, which are stored in Collections.Cloud Firestorecreates collections and documents implicitly
the first time you add data to the document. You do not need to explicitly
create collections or documents.
Create a new collection and a document using the following example code.
Web
import{collection,addDoc}from"firebase/firestore";try{constdocRef=awaitaddDoc(collection(db,"users"),{first:"Ada",last:"Lovelace",born:1815});console.log("Document written with ID: ",docRef.id);}catch(e){console.error("Error adding document: ",e);}
db.collection("users").add({first:"Ada",last:"Lovelace",born:1815}).then((docRef)=>{console.log("Document written with ID: ",docRef.id);}).catch((error)=>{console.error("Error adding document: ",error);});
Note:This product is not available on watchOS and App Clip targets.
// Add a new document with a generated IDdo{letref=tryawaitdb.collection("users").addDocument(data:["first":"Ada","last":"Lovelace","born":1815])print("Document added with ID:\(ref.documentID)")}catch{print("Error adding document:\(error)")}
Note:This product is not available on watchOS and App Clip targets.
// Add a new document with a generated ID__blockFIRDocumentReference*ref=[[self.dbcollectionWithPath:@"users"]addDocumentWithData:@{@"first":@"Ada",@"last":@"Lovelace",@"born":@1815}completion:^(NSError*_Nullableerror){if(error!=nil){NSLog(@"Error adding document: %@",error);}else{NSLog(@"Document added with ID: %@",ref.documentID);}}];
// Create a new user with a first and last namevaluser=hashMapOf("first"to"Ada","last"to"Lovelace","born"to1815,)// Add a new document with a generated IDdb.collection("users").add(user).addOnSuccessListener{documentReference->Log.d(TAG,"DocumentSnapshot added with ID:${documentReference.id}")}.addOnFailureListener{e->Log.w(TAG,"Error adding document",e)}
// Create a new user with a first and last nameMap<String,Object>user=newHashMap<>();user.put("first","Ada");user.put("last","Lovelace");user.put("born",1815);// Add a new document with a generated IDdb.collection("users").add(user).addOnSuccessListener(newOnSuccessListener<DocumentReference>(){@OverridepublicvoidonSuccess(DocumentReferencedocumentReference){Log.d(TAG,"DocumentSnapshot added with ID: "+documentReference.getId());}}).addOnFailureListener(newOnFailureListener(){@OverridepublicvoidonFailure(@NonNullExceptione){Log.w(TAG,"Error adding document",e);}});
// Create a new user with a first and last namefinaluser=<String,dynamic>{"first":"Ada","last":"Lovelace","born":1815};// Add a new document with a generated IDdb.collection("users").add(user).then((DocumentReferencedoc)=>print('DocumentSnapshot added with ID:${doc.id}'));
DocumentReferencedocRef=db.collection("users").document("alovelace");// Add document data with id "alovelace" using a hashmapMap<String,Object>data=newHashMap<>();data.put("first","Ada");data.put("last","Lovelace");data.put("born",1815);//asynchronously write dataApiFuture<WriteResult>result=docRef.set(data);// ...// result.get() blocks on responseSystem.out.println("Update time : "+result.get().getUpdateTime());
// Add a new document with a generated IDFuture<DocumentReference>user_ref=db->Collection("users").Add({{"first", FieldValue::String("Ada")},
{"last", FieldValue::String("Lovelace")},
{"born", FieldValue::Integer(1815)}});user_ref.OnCompletion([](constFuture<DocumentReference>&future){if(future.error()==Error::kErrorOk){std::cout<<"DocumentSnapshot added with ID: "<<future.result()->id()<<std::endl;}else{std::cout<<"Error adding document: "<<future.error_message()<<std::endl;}});
$docRef = $db->collection('samples/php/users')->document('alovelace');$docRef->set(['first' => 'Ada','last' => 'Lovelace','born' => 1815]);printf('Added data to the lovelace document in the users collection.' . PHP_EOL);
DocumentReferencedocRef=db.Collection("users").Document("alovelace");Dictionary<string,object>user=newDictionary<string,object>{{"First","Ada"},{"Last","Lovelace"},{"Born",1815},};docRef.SetAsync(user).ContinueWithOnMainThread(task=>{Debug.Log("Added data to the alovelace document in the users collection.");});
doc_ref=firestore.doc"#{collection_path}/alovelace"doc_ref.set({first:"Ada",last:"Lovelace",born:1815})puts"Added data to the alovelace document in the users collection."
Now add another document to theuserscollection. Notice that this document
includes a key-value pair (middle name) that does not appear in the first
document. Documents in a collection can contain different sets of information.
Web
// Add a second document with a generated ID.import{addDoc,collection}from"firebase/firestore";try{constdocRef=awaitaddDoc(collection(db,"users"),{first:"Alan",middle:"Mathison",last:"Turing",born:1912});console.log("Document written with ID: ",docRef.id);}catch(e){console.error("Error adding document: ",e);}
// Add a second document with a generated ID.db.collection("users").add({first:"Alan",middle:"Mathison",last:"Turing",born:1912}).then((docRef)=>{console.log("Document written with ID: ",docRef.id);}).catch((error)=>{console.error("Error adding document: ",error);});
Note:This product is not available on watchOS and App Clip targets.
// Add a second document with a generated ID.do{letref=tryawaitdb.collection("users").addDocument(data:["first":"Alan","middle":"Mathison","last":"Turing","born":1912])print("Document added with ID:\(ref.documentID)")}catch{print("Error adding document:\(error)")}
Note:This product is not available on watchOS and App Clip targets.
// Add a second document with a generated ID.__blockFIRDocumentReference*ref=[[self.dbcollectionWithPath:@"users"]addDocumentWithData:@{@"first":@"Alan",@"middle":@"Mathison",@"last":@"Turing",@"born":@1912}completion:^(NSError*_Nullableerror){if(error!=nil){NSLog(@"Error adding document: %@",error);}else{NSLog(@"Document added with ID: %@",ref.documentID);}}];
// Create a new user with a first, middle, and last namevaluser=hashMapOf("first"to"Alan","middle"to"Mathison","last"to"Turing","born"to1912,)// Add a new document with a generated IDdb.collection("users").add(user).addOnSuccessListener{documentReference->Log.d(TAG,"DocumentSnapshot added with ID:${documentReference.id}")}.addOnFailureListener{e->Log.w(TAG,"Error adding document",e)}
// Create a new user with a first, middle, and last nameMap<String,Object>user=newHashMap<>();user.put("first","Alan");user.put("middle","Mathison");user.put("last","Turing");user.put("born",1912);// Add a new document with a generated IDdb.collection("users").add(user).addOnSuccessListener(newOnSuccessListener<DocumentReference>(){@OverridepublicvoidonSuccess(DocumentReferencedocumentReference){Log.d(TAG,"DocumentSnapshot added with ID: "+documentReference.getId());}}).addOnFailureListener(newOnFailureListener(){@OverridepublicvoidonFailure(@NonNullExceptione){Log.w(TAG,"Error adding document",e);}});
// Create a new user with a first and last namefinaluser=<String,dynamic>{"first":"Alan","middle":"Mathison","last":"Turing","born":1912};// Add a new document with a generated IDdb.collection("users").add(user).then((DocumentReferencedoc)=>print('DocumentSnapshot added with ID:${doc.id}'));
DocumentReferencedocRef=db.collection("users").document("aturing");// Add document data with an additional field ("middle")Map<String,Object>data=newHashMap<>();data.put("first","Alan");data.put("middle","Mathison");data.put("last","Turing");data.put("born",1912);ApiFuture<WriteResult>result=docRef.set(data);System.out.println("Update time : "+result.get().getUpdateTime());
$docRef = $db->collection('samples/php/users')->document('aturing');$docRef->set(['first' => 'Alan','middle' => 'Mathison','last' => 'Turing','born' => 1912]);printf('Added data to the aturing document in the users collection.' . PHP_EOL);
DocumentReferencedocRef=db.Collection("users").Document("aturing");Dictionary<string,object>user=newDictionary<string,object>{{"First","Alan"},{"Middle","Mathison"},{"Last","Turing"},{"Born",1912}};docRef.SetAsync(user).ContinueWithOnMainThread(task=>{Debug.Log("Added data to the aturing document in the users collection.");});
doc_ref=firestore.doc"#{collection_path}/aturing"doc_ref.set({first:"Alan",middle:"Mathison",last:"Turing",born:1912})puts"Added data to the aturing document in the users collection."
iter:=client.Collection("users").Documents(ctx)for{doc,err:=iter.Next()iferr==iterator.Done{break}iferr!=nil{log.Fatalf("Failed to iterate: %v",err)}fmt.Println(doc.Data())}
CollectionReferenceusersRef=db.Collection("users");usersRef.GetSnapshotAsync().ContinueWithOnMainThread(task=>{QuerySnapshotsnapshot=task.Result;foreach(DocumentSnapshotdocumentinsnapshot.Documents){Debug.Log(String.Format("User: {0}",document.Id));Dictionary<string,object>documentDictionary=document.ToDictionary();Debug.Log(String.Format("First: {0}",documentDictionary["First"]));if(documentDictionary.ContainsKey("Middle")){Debug.Log(String.Format("Middle: {0}",documentDictionary["Middle"]));}Debug.Log(String.Format("Last: {0}",documentDictionary["Last"]));Debug.Log(String.Format("Born: {0}",documentDictionary["Born"]));}Debug.Log("Read all data from the users collection.");});
Here are some basic rule sets you can use to get started. You can modify your
security rules in theRules
tabof
the console.
Auth required
// Allow read/write access to a document keyed by the user's UIDservicecloud.firestore{match/databases/{database}/documents{match/users/{uid}{allowread,write:ifrequest.auth!=null&&request.auth.uid==uid;}}}
Production mode
// Deny read/write access to all users under any conditionsservicecloud.firestore{match/databases/{database}/documents{match/{document=**}{allowread,write:iffalse;}}}
Before you deploy your web, Android, or iOS app to production, also take steps
to ensure that only your app clients can access yourCloud Firestoredata.
See theApp Checkdocumentation.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Missing the information I need","missingTheInformationINeed","thumb-down"],["Too complicated / too many steps","tooComplicatedTooManySteps","thumb-down"],["Out of date","outOfDate","thumb-down"],["Samples / code issue","samplesCodeIssue","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2025-09-04 UTC."],[],[],null,[]]