Get Started with Cloud Firestore

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.6.0/firebase.js"></script>
    <script src="https://www.gstatic.com/firebasejs/4.6.0/firebase-firestore.js"></script>
    The Cloud Firestore SDK is also available as an npm package.
    npm install firebase@4.6.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.4.2'
Java
  1. Add the Firebase Admin SDK to your app:
    • Using Gradle:
      compile 'com.google.firebase:firebase-admin:5.5.0'
      
    • Using Maven:
      <dependency>
        <groupId>com.google.firebase</groupId>
        <artifactId>firebase-admin</artifactId>
        <version>5.5.0</version>
      </dependency>
           
  2. Follow the instructions below to initialize Cloud Firestore with the proper credentials in your environment.
Python
  1. Add the Firebase Admin SDK to your Python app:
    pip install --upgrade firebase-admin
  2. Follow the instructions below to initialize Cloud Firestore with the proper credentials in your environment.
Node.js
  1. Add the Firebase Admin SDK to your app:
    npm install --save firebase-admin@^5.4.0
  2. Follow the instructions below to initialize Cloud Firestore with the proper credentials in your environment.
Go
  1. Add the Firebase Admin SDK to your Go app:
    go get firebase.google.com/go
    
  2. Follow the instructions below to initialize Cloud Firestore with the proper credentials in your environment.

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 defaultStore = 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
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 Google Cloud Platform
    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();
    
  • Initialize on your own server

    To use the Firebase Admin SDK on your own server, use a service account.

    Go to Project Settings > 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.
  • Initialize on Google Cloud Platform
    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()
    
  • Initialize on your own server

    To use the Firebase Admin SDK on your own server, use a service account.

    Go to Project Settings > 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 Project Settings > 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.
  • Initialize on Google Cloud Platform
    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()
    
  • Initialize on your own server

    To use the Firebase Admin SDK on your own server, use a service account.

    Go to Project Settings > 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()
    
  • 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", "Turring");
    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<DocumentSnapshot> documents = querySnapshot.getDocuments();
    for (DocumentSnapshot 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.

    Send feedback about...

    Need help? Visit our support page.