Get started with Cloud Firestore Standard edition Stay organized with collections Save and categorize content based on your preferences.
This quickstart shows you how to set upCloud Firestore, add data, then viewthe data you just added in theFirebase console.
Cloud Firestore supports mobile or web SDKs and server client libraries:
Cloud Firestore supportsSDKs for Android, iOS, and web and more. Combined withCloud Firestore Security Rules andFirebase Authentication, the mobile and web SDKs supportserverless app architectures where clients connect directly to yourCloud Firestore database.
Cloud Firestore supportsserver client libraries for C#, Go, Java, Node.js, PHP,Python, and Ruby. Use these client libraries to set up privileged serverenvironments with full access to your database. Learn more about these librariesin theQuickstart for server client libraries.
Create aCloud Firestore database
If you haven't already, create a Firebase project: In theFirebase console, clickAdd project,then follow the on-screen instructions to create a Firebase project or toadd Firebase services to an existingGoogle Cloud project.
Open your project in theFirebase console. In the left panel, expandBuild and then selectFirestore database.
ClickCreate database.
Select alocation for your database.
If you aren't able to select a location, then your project's"location for defaultGoogle Cloud resources"has already been set. Some of your project's resources (like the defaultCloud Firestore instance) share a common location dependency, andtheir location can be set either during project creation or when setting upanother service that shares this location dependency.
Select a starting mode for yourCloud Firestore Security 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,makesure to review theSecure your data section.
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 Rubyserver client library, select production mode.
Your initial set ofCloud Firestore Security Rules will apply to your defaultCloud Firestore database. If you create multiple databases for yourproject, you can deployCloud Firestore Security Rules for each database.
ClickCreate.
(default) database in standard mode with Datastore or Firestore Native APIs can be used withApp Engine.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.
Web
- Follow the instructions toadd Firebase to your web app.
- TheCloud Firestore SDK is available as an npm package.
You'll need to import both Firebase andCloud Firestore.npminstallfirebase@12.9.0--save
import{initializeApp}from"firebase/app";import{getFirestore}from"firebase/firestore";
Web
- Follow the instructions toadd Firebase to your web app.
- Add the Firebase andCloud Firestore libraries to your app:
TheCloud Firestore SDK is also available as an npm package.<script src="https://www.gstatic.com/firebasejs/12.9.0/firebase-app-compat.js"></script><script src="https://www.gstatic.com/firebasejs/12.9.0/firebase-firestore-compat.js"></script>
You'll need to manually require both Firebase andCloud Firestore.npminstallfirebase@12.9.0--save
importfirebasefrom"firebase/compat/app";//Requiredforside-effectsimport"firebase/firestore";
iOS+
Follow the instructions toadd Firebase to your Apple app.
Use Swift Package Manager to install and manage Firebase dependencies.
Visitour installation guide to learn about the different ways you can add Firebase SDKs to your Apple project, including importing frameworks directly and using CocoaPods.- In Xcode, with your app project open, navigate toFile > Swift Packages > Add Package Dependency.
- When prompted, add the Firebase Apple platforms SDK repository:
- Choose the Firestore library.
- When finished, Xcode will automatically begin resolving and downloading your dependencies in the background.
https://github.com/firebase/firebase-ios-sdk
Android
- Follow the instructions toadd Firebase to your Android app.
- Using theFirebase Android BoM, declare the dependency for theCloud Firestore library for Android in yourmodule (app-level) Gradle file (usually
app/build.gradle.ktsorapp/build.gradle).dependencies{// Import the BoM for the Firebase platformimplementation(platform("com.google.firebase:firebase-bom:34.9.0"))// Declare the dependency for theCloud Firestore library// 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.
(Alternative) Declare Firebase library dependencieswithout using theBoM
If you choose not to use theFirebase BoM, you must specify each Firebase library version in its dependency line.
Note that if you usemultiple Firebase libraries in your app, we highly recommend using theBoM to manage library versions, which ensures that all versions are compatible.
dependencies{// Declare the dependency for theCloud Firestore library// When NOT using the BoM, you must specify versions in Firebase library dependenciesimplementation("com.google.firebase:firebase-firestore:26.1.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).
Dart
- If you haven't already,configure and initialize Firebase in your Flutter app.
- 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 the
target '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 endend
ReplaceIOS_SDK_VERSION with the version of the Firebase iOS SDK specified in
firebase_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:
gem install cocoapods
For more information see theissue on GitHub.
C++
- Follow the instructions toadd Firebase to your C++ project.
- C++ interface for Android.
- Gradle dependencies. Add the following to your module (app-level) Gradle file (usually
app/build.gradle):android.defaultConfig.externalNativeBuild.cmake{arguments"-DFIREBASE_CPP_SDK_DIR=$gradle.firebase_cpp_sdk_dir"}applyfrom:"$gradle.firebase_cpp_sdk_dir/Android/firebase_dependencies.gradle"firebaseCpp.dependencies{// earlier entriesauthfirestore}
- Binary dependencies. Similarly, the recommended way to get the binary dependencies is to add the following to your
CMakeLists.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 set updesktop integration, seeAdd Firebase to your C++ project.
Unity
- Follow the instructions toadd Firebase to your Unity project.
- Use the Unity interface to configure your project to minify Android builds.
- The option can be found inPlayer Settings > Android > Publishing Settings > Minify.
- The options may differ in different versions of Unity so refer to the officialUnity documentation and theFirebase Unity Build Debug Guide.
- If, after enabling minification, the number of referenced methods still exceeds the limit, another option is to enable
multidexin:mainTemplate.gradleifCustom Gradle Template underPlayer Settings is enabled- or, the module-level
build.gradlefile, if you use Android Studio to build the exported project.
You must minify the build to avoid the messageError while merging dex archives.
(Optional) Prototype and test withFirebase Local Emulator Suite
For mobile developers, before talking about how your app writes to and readsfromCloud Firestore, let's introduce a set of tools you can use toprototype and testCloud Firestore functionality:Firebase Local Emulator Suite. If you're trying out different data models,optimizing your security rules, or working to find the most cost-effective wayto interact with the back-end, being able to work locally without deployinglive services can be a great idea.
ACloud Firestore emulator is part of theLocal Emulator Suite, whichenables your app to interact with your emulated database content and config, aswell as optionally your emulated project resources (functions, other databases,and security rules).
Using theCloud Firestore emulator 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, running
firebase emulators:start. - Making calls from your app's prototype code using aCloud Firestore platformSDK as usual.
A detailedwalkthrough involvingCloud Firestore andCloud Functions is available. You should also have a look at theLocal Emulator Suite introduction.
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;
C++
// Make sure the call to `Create()` happens some time before you call Firestore::GetInstance().App::Create();Firestore*db=Firestore::GetInstance();
Unity
usingFirebase.Firestore;usingFirebase.Extensions;
FirebaseFirestoredb=FirebaseFirestore.DefaultInstance;
Add data
Cloud Firestore stores data in Documents, which are stored in Collections.Cloud Firestore creates collections and documents implicitlythe first time you add data to the document. You do not need to explicitlycreate 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);}
Web
Learn more about the tree-shakeable modular Web API and its advantages over the namespaced API.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);});
Swift
// 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)")}
Objective-C
// 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);}}];
Kotlin
// 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)}
Java
// 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);}});
Dart
// 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}'));
C++
// 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;}});
Unity
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.");});
Now add another document to theusers collection. Notice that this documentincludes a key-value pair (middle name) that does not appear in the firstdocument. 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);}
Web
Learn more about the tree-shakeable modular Web API and its advantages over the namespaced API.// 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);});
Swift
// 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)")}
Objective-C
// 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);}}];
Kotlin
// 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)}
Java
// 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);}});
Dart
// 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}'));
C++
db->Collection("users").Add({{"first", FieldValue::String("Alan")}, {"middle", FieldValue::String("Mathison")}, {"last", FieldValue::String("Turing")}, {"born", FieldValue::Integer(1912)}}).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;}});
Unity
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.");});
Read data
Use the data viewer in theFirebase consoleto quickly verify that you've added data toCloud Firestore.
You can also use the "get" method to retrieve the entire collection.
Web
import{collection,getDocs}from"firebase/firestore";constquerySnapshot=awaitgetDocs(collection(db,"users"));querySnapshot.forEach((doc)=>{console.log(`${doc.id} =>${doc.data()}`);});
Web
Learn more about the tree-shakeable modular Web API and its advantages over the namespaced API.db.collection("users").get().then((querySnapshot)=>{querySnapshot.forEach((doc)=>{console.log(`${doc.id} =>${doc.data()}`);});});
Swift
do{letsnapshot=tryawaitdb.collection("users").getDocuments()fordocumentinsnapshot.documents{print("\(document.documentID) =>\(document.data())")}}catch{print("Error getting documents:\(error)")}
Objective-C
[[self.dbcollectionWithPath:@"users"]getDocumentsWithCompletion:^(FIRQuerySnapshot*_Nullablesnapshot,NSError*_Nullableerror){if(error!=nil){NSLog(@"Error getting documents: %@",error);}else{for(FIRDocumentSnapshot*documentinsnapshot.documents){NSLog(@"%@ => %@",document.documentID,document.data);}}}];
Kotlin
db.collection("users").get().addOnSuccessListener{result->for(documentinresult){Log.d(TAG,"${document.id} =>${document.data}")}}.addOnFailureListener{exception->Log.w(TAG,"Error getting documents.",exception)}
Java
db.collection("users").get().addOnCompleteListener(newOnCompleteListener<QuerySnapshot>(){@OverridepublicvoidonComplete(@NonNullTask<QuerySnapshot>task){if(task.isSuccessful()){for(QueryDocumentSnapshotdocument:task.getResult()){Log.d(TAG,document.getId()+" => "+document.getData());}}else{Log.w(TAG,"Error getting documents.",task.getException());}}});
Dart
awaitdb.collection("users").get().then((event){for(vardocinevent.docs){print("${doc.id} =>${doc.data()}");}});
C++
Future<QuerySnapshot>users=db->Collection("users").Get();users.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;}});
Unity
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.");});
Secure your data
If you're using the web, Android, or Apple platforms SDK, useFirebaseAuthentication andCloud Firestore Security Rules to secure your data inCloud Firestore.
Here are some basic rule sets you can use to get started. You can modify yoursecurity rules in theRulestab ofthe 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 stepsto ensure that only your app clients can access yourCloud Firestore data.See theApp Check documentation.
If you're using one of the server SDKs, useIdentity and Access Management(IAM) to secure your datainCloud Firestore.
Watch a video tutorial
For detailed guidance on getting started with theCloud Firestoremobile client libraries, watch one of the following video tutorials:
Web
iOS+
Android
You can find more videos in the FirebaseYouTube channel.
Next steps
Deepen your knowledge with the following topics:
- Codelabs — Learn to useCloud Firestore in a real app byfollowing the codelab forAndroid,iOS, orweb.
- Data model — Learn more about how data isstructured inCloud Firestore, including hierarchical data and subcollections.
- Add data — Learn more about creating and updating data inCloud Firestore.
- Get data — Learn more about how to retrievedata.
- Perform simple and compound queries — Learn how to run simple and compound queries.
- Order and limit queries Learn how to orderand limit the data returned by your queries.
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 2026-02-18 UTC.