Stay organized with collectionsSave and categorize content based on your preferences.
Create a Firestore database by using a web or mobile client library
This quickstart shows you how to set up Firestore, add data, and read
data by using the Android, Apple platforms, Web, Unity, or C++ client library.
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 to
add Firebase services to an existing Google Cloud project.
Open your project in the Firebase console. In the left panel, expandBuildand then selectFirestore database.
If you aren't able to select a location, then your project's"location for default Google Cloud resources"has already been set. Some of your project's resources (like the default
Firestore instance) 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 your 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,make
sure to review theSecure your datasection.
To get started with the web, Apple platforms, or Android SDK, select test mode.
Locked 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 locked mode.
Your initial set of Firestore Security Rules will apply to your default
Firestore database. If you create multiple databases for your project,
you can deploy Firestore Security Rules for each database.
ClickCreate.
When you enable 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.
If your app uses multiple Firebase libraries, consider using theFirebase
Android BoM, which ensures that your app's Firebase library versions
are always compatible.
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).
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}")
or, the module-levelbuild.gradlefile, if you use Android Studio to build the exported project.
Initialize Firestore in Native Mode
Initialize an instance of Firestore:
Web version 9
//InitializeFirestorethroughFirebaseimport{initializeApp}from"firebase/app"import{getFirestore}from"firebase/firestore"constfirebaseApp=initializeApp({apiKey:'### FIREBASE API KEY ###',authDomain:'### FIREBASE AUTH DOMAIN ###',projectId:'### CLOUD FIRESTORE PROJECT ID ###'});constdb=getFirestore();
The values for `initializeApp` can be found in your web app's`firebaseConfig`.
To persist data when the device loses its connection, see theEnable Offline Datadocumentation.
Web version 8
//InitializeFirestorethroughFirebasefirebase.initializeApp({apiKey:'### FIREBASE API KEY ###',authDomain:'### FIREBASE AUTH DOMAIN ###',projectId:'### CLOUD FIRESTORE PROJECT ID ###'});vardb=firebase.firestore();
The values for `initializeApp` can be found in your web app's`firebaseConfig`.
To persist data when the device loses its connection, see theEnable Offline Datadocumentation.
Swift
Note:This product is not available on watchOS and App Clip targets.
Note:This product is not available on watchOS and App Clip targets.
@importFirebaseCore;@importFirebaseFirestore;// Use Firebase library to configure APIs[FIRAppconfigure];FIRFirestore*defaultFirestore=[FIRFirestorefirestore];
Firestore stores data in Documents, which are stored in Collections.
Firestore creates 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 version 9
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}'));
// 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;}});
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 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 version 9
// 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");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 to Firestore.
You can also use thegetmethod to retrieve the entire collection.
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 Firebase console.
Auth required
// Allow read/write access on all documents to any user signed in to the applicationservicecloud.firestore{match/databases/{database}/documents{match/{document=**}{allowread,write:ifrequest.auth!=null;}}}
Locked mode
// Deny read/write access to all users under any conditionsservicecloud.firestore{match/databases/{database}/documents{match/{document=**}{allowread,write:iffalse;}}}
Test mode
// Allow read/write access to all users under any conditions// Warning: **NEVER** use this rule set in production; it allows// anyone to overwrite your entire database.servicecloud.firestore{match/databases/{database}/documents{match/{document=**}{allowread,write:iftrue;}}}
Before you deploy your Web, Android, or iOS app to production, also take steps
to ensure that only your app clients can access your Firestore in Native Mode data.
See theApp Checkdocumentation.
Watch a video tutorial
For detailed guidance on getting started with the Firestore
mobile and web client libraries, watch one of the following video tutorials:
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Hard to understand","hardToUnderstand","thumb-down"],["Incorrect information or sample code","incorrectInformationOrSampleCode","thumb-down"],["Missing the information/samples I need","missingTheInformationSamplesINeed","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2025-09-04 UTC."],[],[],null,[]]