Quickstart

This quickstart shows you how to set up Cloud Firestore, add data, and read data by using the Android, iOS, or Web client library.

Create a Cloud Firestore project

  1. Open the Firebase Console and create a new project. Select a Project name, Analytics and billing region, and a Backend service data location. Click Create Project.

  2. In the Database section, click the Get Started button for Cloud Firestore.

  3. Select Test 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.
  4. 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/5.3.0/firebase-app.js"></script>
    <script src="https://www.gstatic.com/firebasejs/5.3.0/firebase-firestore.js"></script>
    The Cloud Firestore SDK is also available as an npm package.
    npm install firebase@5.3.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:17.1.0'

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();

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

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

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 (QueryDocumentSnapshot document : task.getResult()) {
                        Log.d(TAG, document.getId() + " => " + document.getData());
                    }
                } else {
                    Log.w(TAG, "Error getting documents.", task.getException());
                }
            }
        });

Secure your data

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 Firebase 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;
    }
  }
}

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.
Was this page helpful? Let us know how we did: