Quickstart using a mobile/web client library

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

Create a Firestore database

  1. If you haven't already, create a Firebase project: In the Firebase console, click Add project, then follow the on-screen instructions to create a Firebase project or to add Firebase services to an existing GCP project.

  2. From the Firebase console's navigation pane, select Firestore, then click Create database for Firestore.

  3. Select Test 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 the Secure your data section.
  4. Select a location for your database.

    • This location setting is your project's default Google Cloud Platform (GCP) resource location. Note that this location will be used for GCP services in your project that require a location setting, specifically, your default Cloud Storage bucket and your App Engine app (which is required if you use Cloud Scheduler).

    • If you aren't able to select a location, then your project already has a default GCP resource location. It was set either during project creation or when setting up another service that requires a location setting.

  5. Click Done.

When you enable Firestore, 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 Firestore libraries to your app:
    <script src="https://www.gstatic.com/firebasejs/8.1.1/firebase-app.js"></script>
    <script src="https://www.gstatic.com/firebasejs/8.1.1/firebase-firestore.js"></script>
    The Firestore SDK is also available as an npm package.
    npm install firebase@8.1.1 --save
    
    You'll need to manually require both Firebase and 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 Firestore pod to your Podfile
    pod 'Firebase/Firestore'
    
    # Optionally, include the Swift extensions if you're using Swift.
    pod 'FirebaseFirestoreSwift'
    
  3. Save the file and run pod install.
Java
Android
  1. Follow the instructions to add Firebase to your Android app.
  2. Declare the dependency for the Firestore Android library in your module (app-level) Gradle file (usually app/build.gradle):
    implementation 'com.google.firebase:firebase-firestore:22.0.0'

    If your app uses multiple Firebase libraries, consider using the Firebase Android BoM, which ensures that your app's Firebase library versions are always compatible.

Kotlin+KTX
Android
  1. Follow the instructions to add Firebase to your Android app.
  2. Declare the dependency for the Firestore Android library in your module (app-level) Gradle file (usually app/build.gradle):
    implementation 'com.google.firebase:firebase-firestore-ktx:22.0.0'

    If your app uses multiple Firebase libraries, consider using the Firebase Android BoM, which ensures that your app's Firebase library versions are always compatible.

Initialize Firestore

Initialize an instance of Firestore:

Web
// Initialize 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 Firestore instance from your Activity
  FirebaseFirestore db = FirebaseFirestore.getInstance();
Kotlin+KTX
Android
  // Access a Firestore instance from your Activity
  val db = Firebase.firestore

Add data

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
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+KTX
Android
// Create a new user with a first and last name
val user = hashMapOf(
        "first" to "Ada",
        "last" to "Lovelace",
        "born" to 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)
    }

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+KTX
Android
// Create a new user with a first, middle, and last name
val user = hashMapOf(
        "first" to "Alan",
        "middle" to "Mathison",
        "last" to "Turing",
        "born" to 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)
    }

Read data

To quickly verify that you've added data to 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+KTX
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)
        }

Secure your data

Use Firebase Authentication and Firestore Security Rules to secure your data in 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 != 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 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 Firestore in a real app by following the codelab for Android, iOS, or Web.
  • Data model — Learn more about how data is structured in Firestore, including hierarchical data and subcollections.
  • Add data — Learn more about creating and updating data in 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.