This quickstart shows you how to set up Cloud Firestore, add data, then view the data you just added in the Firebase console.
Create a Cloud Firestore project
Open the Firebase Console and create a new project.
In the Database section, click the Get Started button for Cloud Firestore.
Select a starting mode for your Cloud 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 see the Secure your data section.
To get started with the Web, IOS, 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.
Click Enable.
When you create a Cloud Firestore project, it also enables the API in the Cloud API Manager.
Set up your development environment
Add the required dependencies and client libraries to your app.
Web
- Follow the instructions to add Firebase to your Web app.
- Add the Firebase and Cloud Firestore libraries to your app:
<script src="https://www.gstatic.com/firebasejs/5.8.0/firebase-app.js"></script> <script src="https://www.gstatic.com/firebasejs/5.8.0/firebase-firestore.js"></script>
The Cloud Firestore SDK is also available as an npm package.npm install firebase@5.8.0 --save
You'll need to manually require both Firebase and Cloud Firestore.const firebase = require("firebase"); // Required for side-effects require("firebase/firestore");
iOS
- Follow the instructions to add Firebase to your iOS app.
- Add the Cloud Firestore pod to your
Podfile
pod 'Firebase/Core' pod 'Firebase/Firestore'
- Save the file and run
pod install
.
Android
- Follow the instructions to add Firebase to your Android app.
-
Add the Cloud Firestore Android library to your
app/build.gradle
file:implementation 'com.google.firebase:firebase-firestore:18.0.1'
Java
- Add the Firebase Admin SDK to your app:
-
Using Gradle:
compile 'com.google.firebase:firebase-admin:6.7.0'
-
Using Maven:
<dependency> <groupId>com.google.firebase</groupId> <artifactId>firebase-admin</artifactId> <version>6.7.0</version> </dependency>
-
Using Gradle:
- Follow the instructions below to initialize Cloud Firestore with the proper credentials in your environment.
Python
- Add the Firebase Admin SDK to your Python app:
pip install --upgrade firebase-admin
- Follow the instructions below to initialize Cloud Firestore with the proper credentials in your environment.
Node.js
-
Add the Firebase Admin SDK to your app:
npm install firebase-admin --save
- Follow the instructions below to initialize Cloud Firestore with the proper credentials in your environment.
Go
- Add the Firebase Admin SDK to your Go app:
go get firebase.google.com/go
- Follow the instructions below to initialize Cloud Firestore with the proper credentials in your environment.
PHP
-
The Cloud Firestore server client libraries (Java, Node.js, Python, Go, PHP, C#, and Ruby) use
Google Application Default Credentials
for authentication.
-
To authenticate from your development environment, set the
GOOGLE_APPLICATION_CREDENTIALS
environment variable to point to a JSON service account key file. You can create a key file on the API Console Credentials page.export GOOGLE_APPLICATION_CREDENTIALS="path/to/your/keyfile.json"
- 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 for Cloud Firestore. Otherwise, set up a service account.
-
To authenticate from your development environment, set the
- Install and enable the gRPC extension for PHP, which you will need to use the client library.
-
Add the Cloud Firestore PHP library to your app:
composer require google/cloud-firestore
C#
-
The Cloud Firestore server client libraries (Java, Node.js, Python, Go, PHP, C#, and Ruby) use
Google Application Default Credentials
for authentication.
-
To authenticate from your development environment, set the
GOOGLE_APPLICATION_CREDENTIALS
environment variable to point to a JSON service account key file. You can create a key file on the API Console Credentials page.export GOOGLE_APPLICATION_CREDENTIALS="path/to/your/keyfile.json"
- 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 for Cloud Firestore. Otherwise, set up a service account.
-
To authenticate from your development environment, set the
-
Add the Cloud Firestore C# library to your app in your
.csproj
file:<ItemGroup> <PackageReference Include="Google.Cloud.Firestore" Version="1.0.0-beta11" /> </ItemGroup>
-
Add the following to your
Program.cs
file:using Google.Cloud.Firestore;
Ruby
-
The Cloud Firestore server client libraries (Java, Node.js, Python, Go, PHP, C#, and Ruby) use
Google Application Default Credentials
for authentication.
-
To authenticate from your development environment, set the
GOOGLE_APPLICATION_CREDENTIALS
environment variable to point to a JSON service account key file. You can create a key file on the API Console Credentials page.export GOOGLE_APPLICATION_CREDENTIALS="path/to/your/keyfile.json"
- 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 for Cloud Firestore. Otherwise, set up a service account.
-
To authenticate from your development environment, set the
-
Add the Cloud Firestore Ruby library to your app in your
Gemfile
:gem "google-cloud-firestore"
-
Install dependencies from your
Gemfile
using:bundle install
Initialize Cloud Firestore
Initialize an instance of Cloud Firestore:
Web
// Initialize Cloud Firestore through Firebase firebase.initializeApp({ apiKey: '### FIREBASE API KEY ###', authDomain: '### FIREBASE AUTH DOMAIN ###', projectId: '### CLOUD FIRESTORE PROJECT ID ###' }); var db = firebase.firestore();To persist data when the device loses its connection, see the Enable Offline Data documentation.
Swift
import Firebase FirebaseApp.configure() let db = Firestore.firestore()
Objective-C
@import Firebase; // Use Firebase library to configure APIs [FIRApp configure]; FIRFirestore *defaultFirestore = [FIRFirestore firestore];
Java
Android
// Access a Cloud Firestore instance from your Activity FirebaseFirestore db = FirebaseFirestore.getInstance();
Kotlin
Android
// Access a Cloud Firestore instance from your Activity val db = FirebaseFirestore.getInstance()
Java
The Cloud Firestore SDK is initialized in different ways depending on your environment. Below are the most common methods. For a complete reference, see Initialize the Admin SDK.import com.google.auth.oauth2.GoogleCredentials; import com.google.cloud.firestore.Firestore; import com.google.firebase.FirebaseApp; import com.google.firebase.FirebaseOptions; // Use the application default credentials GoogleCredentials credentials = GoogleCredentials.getApplicationDefault(); FirebaseOptions options = new FirebaseOptions.Builder() .setCredentials(credentials) .setProjectId(projectId) .build(); FirebaseApp.initializeApp(options); Firestore db = FirestoreClient.getFirestore();
To use the Firebase Admin SDK on your own server, use a service account.
Go to IAM & admin > Service accounts in the Cloud Platform Console. Generate a new private key and save the JSON file. Then use the file to initialize the SDK:
import com.google.auth.oauth2.GoogleCredentials; import com.google.cloud.firestore.Firestore; import com.google.firebase.FirebaseApp; import com.google.firebase.FirebaseOptions; // Use a service account InputStream serviceAccount = new FileInputStream("path/to/serviceAccount.json"); GoogleCredentials credentials = GoogleCredentials.fromStream(serviceAccount); FirebaseOptions options = new FirebaseOptions.Builder() .setCredentials(credentials) .build(); FirebaseApp.initializeApp(options); Firestore db = FirestoreClient.getFirestore();
Python
The Cloud Firestore SDK is initialized in different ways depending on your environment. Below are the most common methods. For a complete reference, see Initialize the Admin SDK.import firebase_admin from firebase_admin import credentials from firebase_admin import firestore # Use the application default credentials cred = credentials.ApplicationDefault() firebase_admin.initialize_app(cred, { 'projectId': project_id, }) db = firestore.client()
To use the Firebase Admin SDK on your own server, use a service account.
Go to IAM & admin > Service accounts in the Cloud Platform Console. Generate a new private key and save the JSON file. Then use the file to initialize the SDK:
import firebase_admin from firebase_admin import credentials from firebase_admin import firestore # Use a service account cred = credentials.Certificate('path/to/serviceAccount.json') firebase_admin.initialize_app(cred) db = firestore.client()
Node.js
The Cloud Firestore SDK is initialized in different ways depending on your environment. Below are the most common methods. For a complete reference, see Initialize the Admin SDK.-
Initialize on Cloud Functions
const admin = require('firebase-admin'); const functions = require('firebase-functions'); admin.initializeApp(functions.config().firebase); var db = admin.firestore();
-
Initialize on Google Cloud Platform
const admin = require('firebase-admin'); admin.initializeApp({ credential: admin.credential.applicationDefault() }); var db = admin.firestore();
-
Initialize on your own server
To use the Firebase Admin SDK on your own server (or any other Node.js environment), use a service account. Go to IAM & admin > Service accounts in the Cloud Platform Console. Generate a new private key and save the JSON file. Then use the file to initialize the SDK:
const admin = require('firebase-admin'); var serviceAccount = require('path/to/serviceAccountKey.json'); admin.initializeApp({ credential: admin.credential.cert(serviceAccount) }); var db = admin.firestore();
Go
The Cloud Firestore SDK is initialized in different ways depending on your environment. Below are the most common methods. For a complete reference, see Initialize the Admin SDK.import ( "log" firebase "firebase.google.com/go" "google.golang.org/api/option" ) // Use the application default credentials conf := &firebase.Config{ProjectID: projectID} app, err := firebase.NewApp(ctx, conf) if err != nil { log.Fatalln(err) } client, err := app.Firestore(ctx) if err != nil { log.Fatalln(err) } defer client.Close()
To use the Firebase Admin SDK on your own server, use a service account.
Go to IAM & admin > Service accounts in the Cloud Platform 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 account sa := option.WithCredentialsFile("path/to/serviceAccount.json") app, err := firebase.NewApp(ctx, nil, sa) if err != nil { log.Fatalln(err) } client, err := app.Firestore(ctx) if err != nil { log.Fatalln(err) } defer client.Close()
PHP
use Google\Cloud\Firestore\FirestoreClient; /** * Initialize Cloud Firestore with default project ID. * ``` * initialize(); * ``` */ function initialize() { // Create the Cloud Firestore client $db = new FirestoreClient(); printf('Created Cloud Firestore client with default project ID.' . PHP_EOL); }
C#
FirestoreDb db = FirestoreDb.Create(project); Console.WriteLine("Created Cloud Firestore client with project ID: {0}", project);
Ruby
require "google/cloud/firestore" firestore = Google::Cloud::Firestore.new project_id: project_id puts "Created Cloud Firestore client with given project ID."
Add data
Cloud Firestore stores data in Documents, which are stored in Collections. Cloud 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
db.collection("users").add({ first: "Ada", last: "Lovelace", born: 1815 }) .then(function(docRef) { console.log("Document written with ID: ", docRef.id); }) .catch(function(error) { console.error("Error adding document: ", error); });
Swift
// Add a new document with a generated ID var ref: DocumentReference? = nil ref = db.collection("users").addDocument(data: [ "first": "Ada", "last": "Lovelace", "born": 1815 ]) { err in if let err = err { print("Error adding document: \(err)") } else { print("Document added with ID: \(ref!.documentID)") } }
Objective-C
// Add a new document with a generated ID __block FIRDocumentReference *ref = [[self.db collectionWithPath:@"users"] addDocumentWithData:@{ @"first": @"Ada", @"last": @"Lovelace", @"born": @1815 } completion:^(NSError * _Nullable error) { if (error != nil) { NSLog(@"Error adding document: %@", error); } else { NSLog(@"Document added with ID: %@", ref.documentID); } }];
Java
Android
// Create a new user with a first and last name Map<String, Object> user = new HashMap<>(); user.put("first", "Ada"); user.put("last", "Lovelace"); user.put("born", 1815); // Add a new document with a generated ID db.collection("users") .add(user) .addOnSuccessListener(new OnSuccessListener<DocumentReference>() { @Override public void onSuccess(DocumentReference documentReference) { Log.d(TAG, "DocumentSnapshot added with ID: " + documentReference.getId()); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Log.w(TAG, "Error adding document", e); } });
Kotlin
Android
// Create a new user with a first and last name val user = HashMap<String, Any>() user["first"] = "Ada" user["last"] = "Lovelace" user["born"] = 1815 // Add a new document with a generated ID db.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
DocumentReference docRef = db.collection("users").document("alovelace"); // Add document data with id "alovelace" using a hashmap Map<String, Object> data = new HashMap<>(); data.put("first", "Ada"); data.put("last", "Lovelace"); data.put("born", 1815); //asynchronously write data ApiFuture<WriteResult> result = docRef.set(data); // ... // result.get() blocks on response System.out.println("Update time : " + result.get().getUpdateTime());
Python
doc_ref = db.collection(u'users').document(u'alovelace') doc_ref.set({ u'first': u'Ada', u'last': u'Lovelace', u'born': 1815 })
Node.js
var docRef = db.collection('users').doc('alovelace'); var setAda = docRef.set({ first: 'Ada', last: 'Lovelace', born: 1815 });
Go
_, _, err = client.Collection("users").Add(ctx, map[string]interface{}{ "first": "Ada", "last": "Lovelace", "born": 1815, }) if err != nil { log.Fatalf("Failed adding alovelace: %v", err) }
PHP
$docRef = $db->collection('users')->document('lovelace'); $docRef->set([ 'first' => 'Ada', 'last' => 'Lovelace', 'born' => 1815 ]); printf('Added data to the lovelace document in the users collection.' . PHP_EOL);
C#
DocumentReference docRef = db.Collection("users").Document("alovelace"); Dictionary<string, object> user = new Dictionary<string, object> { { "First", "Ada" }, { "Last", "Lovelace" }, { "Born", 1815 } }; await docRef.SetAsync(user);
Ruby
doc_ref = firestore.doc "users/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 the users
collection. 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. db.collection("users").add({ first: "Alan", middle: "Mathison", last: "Turing", born: 1912 }) .then(function(docRef) { console.log("Document written with ID: ", docRef.id); }) .catch(function(error) { console.error("Error adding document: ", error); });
Swift
// Add a second document with a generated ID. ref = db.collection("users").addDocument(data: [ "first": "Alan", "middle": "Mathison", "last": "Turing", "born": 1912 ]) { err in if let err = err { print("Error adding document: \(err)") } else { print("Document added with ID: \(ref!.documentID)") } }
Objective-C
// Add a second document with a generated ID. __block FIRDocumentReference *ref = [[self.db collectionWithPath:@"users"] addDocumentWithData:@{ @"first": @"Alan", @"middle": @"Mathison", @"last": @"Turing", @"born": @1912 } completion:^(NSError * _Nullable error) { if (error != nil) { NSLog(@"Error adding document: %@", error); } else { NSLog(@"Document added with ID: %@", ref.documentID); } }];
Java
Android
// Create a new user with a first, middle, and last name Map<String, Object> user = new HashMap<>(); user.put("first", "Alan"); user.put("middle", "Mathison"); user.put("last", "Turing"); user.put("born", 1912); // Add a new document with a generated ID db.collection("users") .add(user) .addOnSuccessListener(new OnSuccessListener<DocumentReference>() { @Override public void onSuccess(DocumentReference documentReference) { Log.d(TAG, "DocumentSnapshot added with ID: " + documentReference.getId()); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Log.w(TAG, "Error adding document", e); } });
Kotlin
Android
// Create a new user with a first, middle, and last name val user = HashMap<String, Any>() user["first"] = "Alan" user["middle"] = "Mathison" user["last"] = "Turring" user["born"] = 1912 // Add a new document with a generated ID db.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
DocumentReference docRef = db.collection("users").document("aturing"); // Add document data with an additional field ("middle") Map<String, Object> data = new HashMap<>(); 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());
Python
doc_ref = db.collection(u'users').document(u'aturing') doc_ref.set({ u'first': u'Alan', u'middle': u'Mathison', u'last': u'Turing', u'born': 1912 })
Node.js
var aTuringRef = db.collection('users').doc('aturing'); var setAlan = aTuringRef.set({ 'first': 'Alan', 'middle': 'Mathison', 'last': 'Turing', 'born': 1912 });
Go
_, _, err = client.Collection("users").Add(ctx, map[string]interface{}{ "first": "Alan", "middle": "Mathison", "last": "Turing", "born": 1912, }) if err != nil { log.Fatalf("Failed adding aturing: %v", err) }
PHP
$docRef = $db->collection('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);
C#
DocumentReference docRef = db.Collection("users").Document("aturing"); Dictionary<string, object> user = new Dictionary<string, object> { { "First", "Alan" }, { "Middle", "Mathison" }, { "Last", "Turing" }, { "Born", 1912 } }; await docRef.SetAsync(user);
Ruby
doc_ref = firestore.doc "users/aturing" doc_ref.set({ first: "Alan", middle: "Mathison", last: "Turing", born: 1912 }) puts "Added data to the aturing document in the users collection."
Read data
To quickly verify that you've added data to Cloud Firestore, use the data viewer in the Firebase console.
You can also use the "get" method to retrieve the entire collection.
Web
db.collection("users").get().then((querySnapshot) => { querySnapshot.forEach((doc) => { console.log(`${doc.id} => ${doc.data()}`); }); });
Swift
db.collection("users").getDocuments() { (querySnapshot, err) in if let err = err { print("Error getting documents: \(err)") } else { for document in querySnapshot!.documents { print("\(document.documentID) => \(document.data())") } } }
Objective-C
[[self.db collectionWithPath:@"users"] getDocumentsWithCompletion:^(FIRQuerySnapshot * _Nullable snapshot, NSError * _Nullable error) { if (error != nil) { NSLog(@"Error getting documents: %@", error); } else { for (FIRDocumentSnapshot *document in snapshot.documents) { NSLog(@"%@ => %@", document.documentID, document.data); } } }];
Java
Android
db.collection("users") .get() .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() { @Override public void onComplete(@NonNull Task<QuerySnapshot> task) { if (task.isSuccessful()) { for (QueryDocumentSnapshot document : task.getResult()) { Log.d(TAG, document.getId() + " => " + document.getData()); } } else { Log.w(TAG, "Error getting documents.", task.getException()); } } });
Kotlin
Android
db.collection("users") .get() .addOnSuccessListener { result -> for (document in result) { Log.d(TAG, document.id + " => " + document.data) } } .addOnFailureListener { exception -> Log.w(TAG, "Error getting documents.", exception) }
Java
// asynchronously retrieve all users ApiFuture<QuerySnapshot> query = db.collection("users").get(); // ... // query.get() blocks on response QuerySnapshot querySnapshot = query.get(); List<QueryDocumentSnapshot> documents = querySnapshot.getDocuments(); for (QueryDocumentSnapshot document : documents) { System.out.println("User: " + document.getId()); System.out.println("First: " + document.getString("first")); if (document.contains("middle")) { System.out.println("Middle: " + document.getString("middle")); } System.out.println("Last: " + document.getString("last")); System.out.println("Born: " + document.getLong("born")); }
Python
users_ref = db.collection(u'users') docs = users_ref.get() for doc in docs: print(u'{} => {}'.format(doc.id, doc.to_dict()))
Node.js
db.collection('users').get() .then((snapshot) => { snapshot.forEach((doc) => { console.log(doc.id, '=>', doc.data()); }); }) .catch((err) => { console.log('Error getting documents', err); });
Go
iter := client.Collection("users").Documents(ctx) for { doc, err := iter.Next() if err == iterator.Done { break } if err != nil { log.Fatalf("Failed to iterate: %v", err) } fmt.Println(doc.Data()) }
PHP
$usersRef = $db->collection('users'); $snapshot = $usersRef->documents(); foreach ($snapshot as $user) { printf('User: %s' . PHP_EOL, $user->id()); printf('First: %s' . PHP_EOL, $user['first']); if (!empty($user['middle'])) { printf('Middle: %s' . PHP_EOL, $user['middle']); } printf('Last: %s' . PHP_EOL, $user['last']); printf('Born: %d' . PHP_EOL, $user['born']); printf(PHP_EOL); } printf('Retrieved and printed out all documents from the users collection.' . PHP_EOL);
C#
CollectionReference usersRef = db.Collection("users"); QuerySnapshot snapshot = await usersRef.GetSnapshotAsync(); foreach (DocumentSnapshot document in snapshot.Documents) { Console.WriteLine("User: {0}", document.Id); Dictionary<string, object> documentDictionary = document.ToDictionary(); Console.WriteLine("First: {0}", documentDictionary["First"]); if (documentDictionary.ContainsKey("Middle")) { Console.WriteLine("Middle: {0}", documentDictionary["Middle"]); } Console.WriteLine("Last: {0}", documentDictionary["Last"]); Console.WriteLine("Born: {0}", documentDictionary["Born"]); Console.WriteLine(); }
Ruby
users_ref = firestore.col "users" users_ref.get do |user| puts "#{user.document_id} data: #{user.data}." end
Secure your data
If you're using the Web, Android, or iOS SDK, use Firebase Authentication and Cloud Firestore Security Rules to secure your data in Cloud Firestore.
Here are some basic rule sets you can use to get started. You can modify your security rules in the Rules tab of the console.
Auth required
// Allow read/write access on all documents to any user signed in to the application
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if request.auth.uid != null;
}
}
}
Locked mode
// Deny read/write access to all users under any conditions
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if false;
}
}
}
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.
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if true;
}
}
}
If you're using one of the server SDKs, use Identity and Access Management (IAM) to secure your data in Cloud Firestore.
Watch a video tutorial
For detailed guidance on getting started with the Cloud Firestore mobile and web client libraries, watch one of the following video tutorials:
Web
iOS
Android
You can find more videos in the Firebase YouTube channel.
Next steps
Deepen your knowledge with the following topics:
- Codelabs — Learn to use Cloud Firestore in a real app by following the codelab for Android, iOS, or Web.
- Data model — Learn more about how data is structured in Cloud Firestore, including hierarchical data and subcollections.
- Add data — Learn more about creating and updating data in Cloud Firestore.
- Get data — Learn more about how to retrieve data.
- Perform simple and compound queries — Learn how to run simple and compound queries.
- Order and limit queries Learn how to order and limit the data returned by your queries.