Quickstart

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

  1. Open the Firebase Console and create a new project.

  2. In the Database section, click Try Firestore Beta.

  3. 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
  1. Follow the instructions to add Firebase to your Web app.
  2. Add the Firebase and Cloud Firestore libraries to your app:
    <script src="https://www.gstatic.com/firebasejs/4.9.0/firebase.js"></script>
    <script src="https://www.gstatic.com/firebasejs/4.9.1/firebase-firestore.js"></script>
    The Cloud Firestore SDK is also available as an npm package.
    npm install firebase@4.9.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
  1. Follow the instructions to add Firebase to your iOS app.
  2. Add the Cloud Firestore pod to your Podfile
    pod 'Firebase/Core'
    pod 'Firebase/Firestore'
  3. Save the file and run pod install.
Android
  1. Follow the instructions to add Firebase to your Android app.
  2. Add the Cloud Firestore Android library to your app/build.gradle file:
    compile 'com.google.firebase:firebase-firestore:11.8.0'
Java
  1. The Cloud Firestore server client libraries (Java, Node.js, Python, and Go) 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.
  2. Add the Cloud Firestore Java library to your app:
    • Using Gradle:
      compile 'com.google.cloud:google-cloud-firestore:0.35.0-beta'
      
    • Using Maven:
      <dependency>
        <groupId>com.google.cloud</groupId>
        <artifactId>google-cloud-firestore</artifactId>
        <version>0.34.0-beta</version>
      </dependency>
Python
  1. The Cloud Firestore server client libraries (Java, Node.js, Python, and Go) 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.
  2. Add the Cloud Firestore Python library to your app:
    pip install --upgrade google-cloud-firestore
Node.js
  1. Add the Firebase Admin SDK to your app:
    npm install --save firebase-admin@^5.9.0
  2. Follow the instructions below to initialize Cloud Firestore with the proper credentials in your environment.
Go
  1. The Cloud Firestore server client libraries (Java, Node.js, Python, and Go) 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.
  2. Add the Cloud Firestore Go library to your app:
    go get "cloud.google.com/go"

Initialize Cloud Firestore

Initialize an instance of Cloud Firestore:

Web
firebase.initializeApp({
  apiKey: '### FIREBASE API KEY ###',
  authDomain: '### FIREBASE AUTH DOMAIN ###',
  projectId: '### CLOUD FIRESTORE PROJECT ID ###'
});

// Initialize Cloud Firestore through Firebase
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];
  
Android
// Access a Cloud Firestore instance from your Activity

FirebaseFirestore db = FirebaseFirestore.getInstance();
Java
import com.google.cloud.firestore.Firestore;
import com.google.cloud.firestore.FirestoreOptions;
FirestoreOptions firestoreOptions =
    FirestoreOptions.getDefaultInstance().toBuilder()
        .setProjectId(projectId)
        .build();
Firestore db = firestoreOptions.getService();
Python
from google.cloud import firestore

# Project ID is determined by the GCLOUD_PROJECT environment variable
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
// Sets your Google Cloud Platform project ID.
projectID := "YOUR_PROJECT_ID"

// Get a Firestore client.
client, err := firestore.NewClient(ctx, projectID)
if err != nil {
	log.Fatalf("Failed to create client: %v", err)
}

// Close client when done.
defer client.Close()

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);
      }
    }];
  
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);
            }
        });
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)
}
  

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);
      }
    }];
  
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);
            }
        });
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)
}
  

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);
        }
      }
    }];
  
Android
db.collection("users")
        .get()
        .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if (task.isSuccessful()) {
                    for (DocumentSnapshot document : task.getResult()) {
                        Log.d(TAG, document.getId() + " => " + document.getData());
                    }
                } else {
                    Log.w(TAG, "Error getting documents.", task.getException());
                }
            }
        });
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())
}
  

Secure your data

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.