<br />

This quickstart shows you how to set upCloud Firestore, add data, then view the data you just added in the Firebase console.

## Create aCloud Firestoredatabase

1. If you haven't already, create a Firebase project: In the[Firebaseconsole](https://console.firebase.google.com/), click**Add project** , then follow the on-screen instructions to create a Firebase project or to add Firebase services to an existingGoogle Cloudproject.

2. Open your project in theFirebaseconsole. In the left panel, expand**Build** and then select[**Firestore database**](https://console.firebase.google.com/project/_/firestore/).

3. Click**Create database**.

4. Select a[location](https://firebase.google.com/docs/firestore/locations#types)for your database.

   If you aren't able to select a location, then your project's["location for defaultGoogle Cloudresources"](https://firebase.google.com/docs/firestore/locations#default-cloud-location)has already been set. Some of your project's resources (like the defaultCloud Firestoreinstance) share a common location dependency, and their location can be set either during project creation or when setting up another service that shares this location dependency.
5. Select a starting mode for yourCloud FirestoreSecurity 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](https://firebase.google.com/docs/firestore/quickstart#secure_your_data)section.**

   :   To get started with the web, Apple platforms, or Android SDK, select test mode.

   Production 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 production mode.

   Your initial set ofCloud FirestoreSecurity Ruleswill apply to your defaultCloud Firestoredatabase. If you create multiple databases for your project, you can deployCloud FirestoreSecurity Rulesfor each database.
6. Click**Create**.

| **Cloud FirestoreandApp Engine:** You can't use bothCloud FirestoreandDatastorein the same project, which might affect apps usingApp Engine. Try usingCloud Firestorewith a different project.

When you enableCloud Firestore, it also enables the API in the[Cloud API Manager](https://console.cloud.google.com/projectselector/apis/api/firestore.googleapis.com/overview).

## 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](https://firebase.google.com/docs/web/setup?sdk_version=v9).
2. TheCloud FirestoreSDK is available as an npm package.  

   ```objective-c
   npm install firebase@12.6.0 --save
   ```
   You'll need to import both Firebase andCloud Firestore.  

   ```python
   import { initializeApp } from "firebase/app";
   import { getFirestore } from "firebase/firestore";
   ```

| Looking for a compact Firestore library, and only need simple REST/CRUD capabilities? Try the[Firestore Lite SDK](https://firebase.google.com/docs/firestore/solutions/firestore-lite), available only via npm.

### Web

1. Follow the instructions to[add Firebase to your web app](https://firebase.google.com/docs/web/setup).
2. Add the Firebase andCloud Firestorelibraries to your app:  

   ```text
   <script src="https://www.gstatic.com/firebasejs/12.6.0/firebase-app-compat.js"></script>
   <script src="https://www.gstatic.com/firebasejs/12.6.0/firebase-firestore-compat.js"></script>
   ```
   TheCloud FirestoreSDK is also available as an npm package.  

   ```objective-c
   npm install firebase@12.6.0 --save
   ```
   You'll need to manually require both Firebase andCloud Firestore.  

   ```python
   import firebase from "firebase/compat/app";
   // Required for side-effects
   import "firebase/firestore";
   ```

##### iOS+

Follow the instructions to[add Firebase to your Apple app](https://firebase.google.com/docs/ios/setup).

Use Swift Package Manager to install and manage Firebase dependencies.
| Visit[our installation guide](https://firebase.google.com/docs/ios/installation-methods)to learn about the different ways you can add Firebase SDKs to your Apple project, including importing frameworks directly and using CocoaPods.

1. In Xcode, with your app project open, navigate to**File \> Swift Packages \> Add Package Dependency**.
2. When prompted, add the Firebase Apple platforms SDK repository:  

```text
  https://github.com/firebase/firebase-ios-sdk
  
```
| **Note:**New projects should use the default (latest) SDK version, but you can choose an older version if needed.
3. Choose the Firestore library.
4. When finished, Xcode will automatically begin resolving and downloading your dependencies in the background.

##### Android

1. Follow the instructions to[add Firebase to your Android app](https://firebase.google.com/docs/android/setup).
2. Using the[Firebase Android BoM](https://firebase.google.com/docs/android/learn-more#bom), declare the dependency for theCloud Firestorelibrary for Android in your**module (app-level) Gradle file** (usually`app/build.gradle.kts`or`app/build.gradle`).  

   ```carbon
   dependencies {
       // Import the BoM for the Firebase platform
       implementation(platform("com.google.firebase:firebase-bom:34.6.0"))

       // Declare the dependency for the Cloud Firestore library
       // When using the BoM, you don't specify versions in Firebase library dependencies
       implementation("com.google.firebase:firebase-firestore")
   }
   ```

   By using the[Firebase Android BoM](https://firebase.google.com/docs/android/learn-more#bom), your app will always use compatible versions of the Firebase Android libraries.  
   *(Alternative)* Declare Firebase library dependencies*without* using theBoM

   If you choose not to use theFirebase BoM, you must specify each Firebase library version in its dependency line.

   **Note that if you use*multiple* Firebase libraries in your app, we highly recommend using theBoMto manage library versions, which ensures that all versions are compatible.**  

   ```carbon
   dependencies {
       // Declare the dependency for the Cloud Firestore library
       // When NOT using the BoM, you must specify versions in Firebase library dependencies
       implementation("com.google.firebase:firebase-firestore:26.0.2")
   }
   ```

   **Looking for a Kotlin-specific library module?** Starting with the[October 2023 release](https://firebase.google.com/support/release-notes/android#2023-10-10), both Kotlin and Java developers can depend on the main library module (for details, see the[FAQ about this initiative](https://firebase.google.com/docs/android/kotlin-migration)).

### Dart

1. If you haven't already,[configure and initialize Firebase](https://firebase.google.com/docs/flutter/setup)in your Flutter app.
2. From the root of your Flutter project, run the following command to install the plugin:  

   ```
   flutter pub add cloud_firestore
   ```
3. Once complete, rebuild your Flutter application:  

   ```
   flutter run
   ```
4. **Optional:** Improve iOS \& macOS build times by including the pre-compiled framework.

   Currently, the Firestore SDK for iOS depends on code that can take upwards of 5 minutes to build in Xcode. To reduce build times significantly, you can use a pre-compiled version by adding this line to the`target 'Runner' do`block in your Podfile:  

   ```
   target 'Runner' do
     use_frameworks!
     use_modular_headers!

     pod 'FirebaseFirestore',
       :git => 'https://github.com/invertase/firestore-ios-sdk-frameworks.git',
       :tag => '<var translate="no">IOS_SDK_VERSION</var>'

     flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))
     target 'RunnerTests' do
       inherit! :search_paths
     end
   end
   ```

   Replace<var translate="no">IOS_SDK_VERSION</var>with the version of the Firebase iOS SDK specified in`firebase_core`'s[`firebase_sdk_version.rb`](https://github.com/firebase/flutterfire/blob/main/packages/firebase_core/firebase_core/ios/firebase_sdk_version.rb#L3)file. If you're not using the latest version of`firebase_core`, look for this file in your local Pub package cache (usually`~/.pub-cache`).

   Additionally, ensure that you have upgraded CocoaPods to 1.9.1 or higher:  

   ```
   gem install cocoapods
   ```

   <br />

   For more information see the[issue on GitHub](https://github.com/FirebaseExtended/flutterfire/issues/2751).

##### Java

1. Add the Firebase Admin SDK to your app:
   - **Using Gradle:**  

     ```java
     implementation 'com.google.firebase:firebase-admin:9.7.0'
     ```
   - **Using Maven:**  

     ```java
     <dependency>
       <groupId>com.google.firebase</groupId>
       <artifactId>firebase-admin</artifactId>
       <version>9.7.0</version>
     </dependency>
          
     ```
2. Follow the instructions below to initializeCloud Firestorewith the proper credentials in your environment.

##### Python

1. Add the Firebase Admin SDK to your Python app:  

   ```python
   pip install --upgrade firebase-admin
   ```
2. Follow the instructions below to initializeCloud Firestorewith the proper credentials in your environment.

##### C++

1. Follow the instructions to[add Firebase to your C++ project](https://firebase.google.com/docs/cpp/setup).
2. **C++ interface for Android.**
   - **Gradle dependencies.** Add the following to your module (app-level) Gradle file (usually`app/build.gradle`):  

     ```c++
             android.defaultConfig.externalNativeBuild.cmake {
               arguments "-DFIREBASE_CPP_SDK_DIR=$gradle.firebase_cpp_sdk_dir"
             }

             apply from: "$gradle.firebase_cpp_sdk_dir/Android/firebase_dependencies.gradle"
             firebaseCpp.dependencies {
               // earlier entries
               auth
               firestore
             }
             
     ```
   - **Binary dependencies.** Similarly, the recommended way to get the binary dependencies is to add the following to your`CMakeLists.txt`file:  

     ```c++
             add_subdirectory(${FIREBASE_CPP_SDK_DIR} bin/ EXCLUDE_FROM_ALL)
             set(firebase_libs firebase_auth firebase_firestore firebase_app)
             # Replace the target name below with the actual name of your target,
             # for example, "native-lib".
             target_link_libraries(${YOUR_TARGET_NAME_HERE} "${firebase_libs}")
             
     ```
3. To set up**desktop integration** , see[Add Firebase to your C++ project](https://firebase.google.com/docs/cpp/setup#desktop-workflow).

##### Unity

1. Follow the instructions to[add Firebase to your Unity project](https://firebase.google.com/docs/unity/setup).
2. Use the Unity interface to configure your project to minify Android builds.
3. You must minify the build to avoid the message`Error while merging dex archives`.
   - The option can be found in**Player Settings \> Android \> Publishing Settings \> Minify**.
   - The options may differ in different versions of Unity so refer to the official[Unity documentation](https://docs.unity3d.com/Manual/class-PlayerSettingsAndroid.html#minify)and the[Firebase Unity Build Debug Guide](https://firebase.google.com/docs/unity/build-debug-guide#single_dex_issues_and_minification_mandatory_if_using_cloud_firestore).
   - If, after enabling minification, the number of referenced methods still exceeds the limit, another option is to enable`multidex`in:
     - `mainTemplate.gradle`if**Custom Gradle Template** under**Player Settings**is enabled
     - or, the module-level`build.gradle`file, if you use Android Studio to build the exported project.

##### Node.js

1. Add the Firebase Admin SDK to your app:  

   ```javascript
   npm install firebase-admin --save
   ```
2. Follow the instructions below to initializeCloud Firestorewith the proper credentials in your environment.

##### Go

1. Add the Firebase Admin SDK to your Go app:  

   ```go
   go get firebase.google.com/go
   ```
2. Follow the instructions below to initializeCloud Firestorewith the proper credentials in your environment.

##### PHP

1. TheCloud Firestoreserver client libraries (Java, Node.js, Python, Go, PHP, C#, and Ruby) use[Google Application Default Credentials](https://cloud.google.com/docs/authentication/production)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](https://console.cloud.google.com/projectselector/apis/credentials).  

     ```php
     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 forCloud Firestore. Otherwise,[set up a service account](https://cloud.google.com/docs/authentication/getting-started).
2. Install and enable the[gRPC extension](https://docs.cloud.google.com/php/docs/reference/help/grpc)for PHP, which you will need to use the client library.
3. Add the Cloud Firestore PHP library to your app:  

   ```php
   composer require google/cloud-firestore
   ```

##### C#

1. TheCloud Firestoreserver client libraries (Java, Node.js, Python, Go, PHP, C#, and Ruby) use[Google Application Default Credentials](https://cloud.google.com/docs/authentication/production)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](https://console.cloud.google.com/projectselector/apis/credentials).  

     ```c#
     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 forCloud Firestore. Otherwise,[set up a service account](https://cloud.google.com/docs/authentication/getting-started).
2. Add the Cloud Firestore C# library to your app in your`.csproj`file:  

   ```c#
   <ItemGroup>
     <PackageReference Include="Google.Cloud.Firestore" Version="1.1.0-beta01" />
   </ItemGroup>
   ```
3. Add the following to your`Program.cs`file:  

   ```c#
   using Google.Cloud.Firestore;
   ```

##### Ruby

1. TheCloud Firestoreserver client libraries (Java, Node.js, Python, Go, PHP, C#, and Ruby) use[Google Application Default Credentials](https://cloud.google.com/docs/authentication/production)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](https://console.cloud.google.com/projectselector/apis/credentials).  

     ```ruby
     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 forCloud Firestore. Otherwise,[set up a service account](https://cloud.google.com/docs/authentication/getting-started).
2. Add the Cloud Firestore Ruby library to your app in your`Gemfile`:  

   ```ruby
   gem "google-cloud-firestore"
   ```
3. Install dependencies from your`Gemfile`using:  

   ```ruby
   bundle install
   ```

## (Optional) Prototype and test withFirebase Local Emulator Suite

For mobile developers, before talking about how your app writes to and reads fromCloud Firestore, let's introduce a set of tools you can use to prototype and testCloud Firestorefunctionality:Firebase Local Emulator Suite. If you're trying out different data models, optimizing your security rules, or working to find the most cost-effective way to interact with the back-end, being able to work locally without deploying live services can be a great idea.

ACloud Firestoreemulator is part of theLocal Emulator Suite, which enables your app to interact with your emulated database content and config, as well as optionally your emulated project resources (functions, other databases, and security rules).

Using theCloud Firestoreemulator involves just a few steps:

1. Adding a line of code to your app's test config to connect to the emulator.
2. From the root of your local project directory, running`firebase emulators:start`.
3. Making calls from your app's prototype code using aCloud Firestoreplatform SDK as usual.

A detailed[walkthrough involvingCloud FirestoreandCloud Functions](https://firebase.google.com/docs/emulator-suite/connect_and_prototype?database=Firestore)is available. You should also have a look at the[Local Emulator Suiteintroduction](https://firebase.google.com/docs/emulator-suite).

## InitializeCloud Firestore

Initialize an instance ofCloud Firestore:  

### Web

```python
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";

// TODO: Replace the following with your app's Firebase project configuration
// See: https://support.google.com/firebase/answer/7015592
const firebaseConfig = {
    FIREBASE_CONFIGURATION
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);


// Initialize Cloud Firestore and get a reference to the service
const db = getFirestore(app);
```

Replace<var translate="no">FIREBASE_CONFIGURATION</var>with your web app's[`firebaseConfig`](https://support.google.com/firebase/answer/7015592).

To persist data when the device loses its connection, see the[Enable Offline Data](https://firebase.google.com/docs/firestore/manage-data/enable-offline)documentation.

### Web

```python
import firebase from "firebase/app";
import "firebase/firestore";

// TODO: Replace the following with your app's Firebase project configuration
// See: https://support.google.com/firebase/answer/7015592
const firebaseConfig = {
    FIREBASE_CONFIGURATION
};

// Initialize Firebase
firebase.initializeApp(firebaseConfig);


// Initialize Cloud Firestore and get a reference to the service
const db = firebase.firestore();
```

Replace<var translate="no">FIREBASE_CONFIGURATION</var>with your web app's[`firebaseConfig`](https://support.google.com/firebase/answer/7015592).

To persist data when the device loses its connection, see the[Enable Offline Data](https://firebase.google.com/docs/firestore/manage-data/enable-offline)documentation.

##### Swift

**Note:**This product is not available on watchOS and App Clip targets.  

```python
import FirebaseCore
import FirebaseFirestore
```  

```swift
FirebaseApp.configure()

let db = Firestore.firestore()https://github.com/firebase/snippets-ios/blob/6b288cfa45a67c92c5db32953f028f8ed9e5a81b/firestore/swift/firestore-smoketest/AppDelegate.swift#L31-L33
```

##### Objective-C

**Note:**This product is not available on watchOS and App Clip targets.  

```python
@import FirebaseCore;
@import FirebaseFirestore;

// Use Firebase library to configure APIs
[FIRApp configure];
  
```  

```objective-c
FIRFirestore *defaultFirestore = [FIRFirestore firestore];https://github.com/firebase/snippets-ios/blob/6b288cfa45a67c92c5db32953f028f8ed9e5a81b/firestore/objc/firestore-smoketest-objc/AppDelegate.m#L32-L32
```

### Kotlin

```kotlin
// Access a Cloud Firestore instance from your Activity
```  

```kotlin
val db = Firebase.firestore  
https://github.com/firebase/snippets-android/blob/294e0edf389e04ad85622081afb988aed37c20fb/firestore/app/src/main/java/com/google/example/firestore/kotlin/DocSnippets.kt#L109-L109
```

### Java

```java
// Access a Cloud Firestore instance from your Activity
```  

```java
FirebaseFirestore db = FirebaseFirestore.getInstance();https://github.com/firebase/snippets-android/blob/294e0edf389e04ad85622081afb988aed37c20fb/firestore/app/src/main/java/com/google/example/firestore/DocSnippets.java#L131-L131
```

### Dart

```dart
db = FirebaseFirestore.instance;
```

##### Java

TheCloud FirestoreSDK is initialized in different ways depending on your environment. Below are the most common methods. For a complete reference, see[Initialize the Admin SDK](https://firebase.google.com/docs/admin/setup#initialize-sdk).
- **Initialize onGoogle Cloud**  

  ```java
  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](https://cloud.google.com/compute/docs/authentication).

  Go to[**IAM \& admin \> Service accounts**](https://console.cloud.google.com/iam-admin/serviceaccounts)in the Google Cloud console. Generate a new private key and save the JSON file. Then use the file to initialize the SDK:  

  ```java
  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("<var translate="no">path/to/serviceAccount.json</var>");
  GoogleCredentials credentials = GoogleCredentials.fromStream(serviceAccount);
  FirebaseOptions options = new FirebaseOptions.Builder()
      .setCredentials(credentials)
      .build();
  FirebaseApp.initializeApp(options);

  Firestore db = FirestoreClient.getFirestore();
  ```

##### Python

TheCloud FirestoreSDK is initialized in different ways depending on your environment. Below are the most common methods. For a complete reference, see[Initialize the Admin SDK](https://firebase.google.com/docs/admin/setup#initialize-sdk).
- **Initialize onGoogle Cloud**  

  ```python
  import firebase_admin
  from firebase_admin import firestore

  # Application Default credentials are automatically created.
  app = firebase_admin.initialize_app()
  db = firestore.client()https://github.com/firebase/firebase-admin-python/blob/fc6c8ee67ea29fe498e7cfca907a5c9fa41a3fed/snippets/firestore/firestore.py#L20-L25
  ```

  An existing application default credential can also be used to initialize the SDK.  

  ```python
  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)
  db = firestore.client()https://github.com/firebase/firebase-admin-python/blob/fc6c8ee67ea29fe498e7cfca907a5c9fa41a3fed/snippets/firestore/firestore.py#L30-L38
  ```
- **Initialize on your own server**

  To use the Firebase Admin SDK on your own server, use a[service account](https://cloud.google.com/compute/docs/authentication).

  Go to[**IAM \& admin \> Service accounts**](https://console.cloud.google.com/iam-admin/serviceaccounts)in the Google Cloud console. Generate a new private key and save the JSON file. Then use the file to initialize the SDK:  

  ```python
  import firebase_admin
  from firebase_admin import credentials
  from firebase_admin import firestore

  # Use a service account.
  cred = credentials.Certificate('path/to/serviceAccount.json')

  app = firebase_admin.initialize_app(cred)

  db = firestore.client()https://github.com/firebase/firebase-admin-python/blob/fc6c8ee67ea29fe498e7cfca907a5c9fa41a3fed/snippets/firestore/firestore.py#L43-L52
  ```

### Python

TheCloud FirestoreSDK is initialized in different ways depending on your environment. Below are the most common methods. For a complete reference, see[Initialize the Admin SDK](https://firebase.google.com/docs/admin/setup#initialize-sdk).
- **Initialize onGoogle Cloud**  

  ```python
  import firebase_admin
  from firebase_admin import firestore_async

  # Application Default credentials are automatically created.
  app = firebase_admin.initialize_app()
  db = firestore_async.client()https://github.com/firebase/firebase-admin-python/blob/fc6c8ee67ea29fe498e7cfca907a5c9fa41a3fed/snippets/firestore/firestore_async.py#L22-L27
  ```

  An existing application default credential can also be used to initialize the SDK.  

  ```python
  import firebase_admin
  from firebase_admin import credentials
  from firebase_admin import firestore_async

  # Use the application default credentials.
  cred = credentials.ApplicationDefault()

  firebase_admin.initialize_app(cred)
  db = firestore_async.client()https://github.com/firebase/firebase-admin-python/blob/fc6c8ee67ea29fe498e7cfca907a5c9fa41a3fed/snippets/firestore/firestore_async.py#L32-L40
  ```
- **Initialize on your own server**

  To use the Firebase Admin SDK on your own server, use a[service account](https://cloud.google.com/compute/docs/authentication).

  Go to[**IAM \& admin \> Service accounts**](https://console.cloud.google.com/iam-admin/serviceaccounts)in the Google Cloud console. Generate a new private key and save the JSON file. Then use the file to initialize the SDK:  

  ```python
  import firebase_admin
  from firebase_admin import credentials
  from firebase_admin import firestore_async

  # Use a service account.
  cred = credentials.Certificate('path/to/serviceAccount.json')

  app = firebase_admin.initialize_app(cred)

  db = firestore_async.client()https://github.com/firebase/firebase-admin-python/blob/fc6c8ee67ea29fe498e7cfca907a5c9fa41a3fed/snippets/firestore/firestore_async.py#L45-L54
  ```

##### C++

```c++
// Make sure the call to `Create()` happens some time before you call Firestore::GetInstance().
App::Create();
Firestore* db = Firestore::GetInstance();https://github.com/firebase/snippets-cpp/blob/778b6bcc8e8e8fcabb1c2e3a8d11ab51a26aa77b/firestore/ios/firestore-snippets-cpp/AppDelegate.mm#L34-L36
```

##### Node.js

TheCloud FirestoreSDK is initialized in different ways depending on your environment. Below are the most common methods. For a complete reference, see[Initialize the Admin SDK](https://firebase.google.com/docs/admin/setup#initialize-sdk).

- **Initialize onCloud Functions**  

  ```javascript
  const { initializeApp, applicationDefault, cert } = require('firebase-admin/app');
  const { getFirestore, Timestamp, FieldValue, Filter } = require('firebase-admin/firestore');
  ```  

  ```javascript
  initializeApp();

  const db = getFirestore();
  https://github.com/firebase/snippets-node/blob/4738eab0d52a393e4e3027e7a6992fd6c892faf2/firestore/main/index.js#L45-L48
  ```
- **Initialize onGoogle Cloud**  

  ```javascript
  const { initializeApp, applicationDefault, cert } = require('firebase-admin/app');
  const { getFirestore, Timestamp, FieldValue, Filter } = require('firebase-admin/firestore');
  ```  

  ```javascript
  initializeApp({
    credential: applicationDefault()
  });

  const db = getFirestore();https://github.com/firebase/snippets-node/blob/4738eab0d52a393e4e3027e7a6992fd6c892faf2/firestore/main/index.js#L30-L35
  ```
- **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](https://cloud.google.com/compute/docs/authentication). Go to[**IAM \& admin \> Service accounts**](https://console.cloud.google.com/iam-admin/serviceaccounts)in the Google Cloud console. Generate a new private key and save the JSON file. Then use the file to initialize the SDK:  

  ```javascript
  const { initializeApp, applicationDefault, cert } = require('firebase-admin/app');
  const { getFirestore, Timestamp, FieldValue, Filter } = require('firebase-admin/firestore');
  ```  

  ```javascript
  const serviceAccount = require('./path/to/serviceAccountKey.json');

  initializeApp({
    credential: cert(serviceAccount)
  });

  const db = getFirestore();
  https://github.com/firebase/snippets-node/blob/4738eab0d52a393e4e3027e7a6992fd6c892faf2/firestore/main/index.js#L55-L63
  ```

##### Go

TheCloud FirestoreSDK is initialized in different ways depending on your environment. Below are the most common methods. For a complete reference, see[Initialize the Admin SDK](https://firebase.google.com/docs/admin/setup#initialize-sdk).
- **Initialize onGoogle Cloud**  

  ```go
  import (
    "log"

    firebase "firebase.google.com/go"
    "google.golang.org/api/option"
  )

  // Use the application default credentials
  ctx := context.Background()
  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](https://cloud.google.com/compute/docs/authentication).

  Go to[**IAM \& admin \> Service accounts**](https://console.cloud.google.com/iam-admin/serviceaccounts)in the Google Cloud console. Generate a new private key and save the JSON file. Then use the file to initialize the SDK:  

  ```go
  import (
    "log"

    firebase "firebase.google.com/go"
    "google.golang.org/api/option"
  )

  // Use a service account
  ctx := context.Background()
  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

### PHP

For more on installing and creating aCloud Firestoreclient, refer to[Cloud FirestoreClient Libraries](https://firebase.google.com/firestore/docs/reference/libraries).  

    use Google\Cloud\Firestore\FirestoreClient;

    /**
     * Initialize Cloud Firestore with default project ID.
     */
    function setup_client_create(string $projectId = null)
    {
        // Create the Cloud Firestore client
        if (empty($projectId)) {
            // The `projectId` parameter is optional and represents which project the
            // client will act on behalf of. If not supplied, the client falls back to
            // the default project inferred from the environment.
            $db = new FirestoreClient();
            printf('Created Cloud Firestore client with default project ID.' . PHP_EOL);
        } else {
            $db = new FirestoreClient([
                'projectId' => $projectId,
            ]);
            printf('Created Cloud Firestore client with project ID: %s' . PHP_EOL, $projectId);
        }
    }  
    https://github.com/GoogleCloudPlatform/php-docs-samples/blob/54369af5505ba98a554966e4f451819ec63cc74a/firestore/src/setup_client_create.php#L27-L47

##### Unity

```c#
using Firebase.Firestore;
using Firebase.Extensions;
```  

```c#
FirebaseFirestore db = FirebaseFirestore.DefaultInstance;
```

##### C#

### C#

For more on installing and creating aCloud Firestoreclient, refer to[Cloud FirestoreClient Libraries](https://firebase.google.com/firestore/docs/reference/libraries).  

    FirestoreDb db = FirestoreDb.Create(project);
    Console.WriteLine("Created Cloud Firestore client with project ID: {0}", project);  
    https://github.com/GoogleCloudPlatform/dotnet-docs-samples/blob/7c95aa33b780cf05c9d699b3c664812d40629c35/firestore/api/Quickstart/Program.cs#L37-L38

##### Ruby

    require "google/cloud/firestore"

    # The `project_id` parameter is optional and represents which project the
    # client will act on behalf of. If not supplied, the client falls back to the
    # default project inferred from the environment.
    firestore = Google::Cloud::Firestore.new project_id: project_id

    puts "Created Cloud Firestore client with given project ID."  
    https://github.com/googleapis/google-cloud-ruby/blob/2248768197f89409e73f1161967200da9f77459a/google-cloud-firestore/samples/quickstart.rb#L19-L26

## Add data

Cloud Firestorestores data in Documents, which are stored in Collections.Cloud Firestorecreates 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

```javascript
import { collection, addDoc } from "firebase/firestore"; 

try {
  const docRef = await addDoc(collection(db, "users"), {
    first: "Ada",
    last: "Lovelace",
    born: 1815
  });
  console.log("Document written with ID: ", docRef.id);
} catch (e) {
  console.error("Error adding document: ", e);
}https://github.com/firebase/snippets-web/blob/95c8c159ff4d90af442352f058406f1aeb8adcbb/snippets/firestore-next/test-firestore/add_ada_lovelace.js#L8-L19
```

### Web

[Learn more](https://firebase.google.com/docs/web/learn-more#modular-version)about the tree-shakeable modular Web API and its advantages over the namespaced API.  

```javascript
db.collection("users").add({
    first: "Ada",
    last: "Lovelace",
    born: 1815
})
.then((docRef) => {
    console.log("Document written with ID: ", docRef.id);
})
.catch((error) => {
    console.error("Error adding document: ", error);
});https://github.com/firebase/snippets-web/blob/95c8c159ff4d90af442352f058406f1aeb8adcbb/firestore/test.firestore.js#L125-L135
```

##### Swift

**Note:**This product is not available on watchOS and App Clip targets.  

```swift
// Add a new document with a generated ID
do {
  let ref = try await db.collection("users").addDocument(data: [
    "first": "Ada",
    "last": "Lovelace",
    "born": 1815
  ])
  print("Document added with ID: \(ref.documentID)")
} catch {
  print("Error adding document: \(error)")
}https://github.com/firebase/snippets-ios/blob/6b288cfa45a67c92c5db32953f028f8ed9e5a81b/firestore/swift/firestore-smoketest/ViewController.swift#L172-L182
```

##### Objective-C

**Note:**This product is not available on watchOS and App Clip targets.  

```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);
      }
    }];https://github.com/firebase/snippets-ios/blob/6b288cfa45a67c92c5db32953f028f8ed9e5a81b/firestore/objc/firestore-smoketest-objc/ViewController.m#L92-L104
```

### Kotlin

```kotlin
// 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)
    }https://github.com/firebase/snippets-android/blob/294e0edf389e04ad85622081afb988aed37c20fb/firestore/app/src/main/java/com/google/example/firestore/kotlin/DocSnippets.kt#L137-L152
```

### Java

```java
// 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);
            }
        });https://github.com/firebase/snippets-android/blob/294e0edf389e04ad85622081afb988aed37c20fb/firestore/app/src/main/java/com/google/example/firestore/DocSnippets.java#L163-L183
```

### Dart

```dart
// Create a new user with a first and last name
final user = <String, dynamic>{
  "first": "Ada",
  "last": "Lovelace",
  "born": 1815
};

// Add a new document with a generated ID
db.collection("users").add(user).then((DocumentReference doc) =>
    print('DocumentSnapshot added with ID: ${doc.id}'));https://github.com/firebase/snippets-flutter/blob/f674af111fe63779c39e79699f7d269231f77563/packages/firebase_snippets_app/lib/snippets/firestore.dart#L44-L53
```

##### 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());  
    https://github.com/googleapis/java-firestore/blob/fa478387d1cefe1ec0909cd37fb28e0b5ec97e63/samples/snippets/src/main/java/com/example/firestore/Quickstart.java#L84-L94

##### Python

    doc_ref = db.collection("users").document("alovelace")
    doc_ref.set({"first": "Ada", "last": "Lovelace", "born": 1815})  
    https://github.com/GoogleCloudPlatform/python-docs-samples/blob/eff0040dee2bab9c4684f8425aa4d8ef28a9a244/firestore/cloud-client/snippets.py#L42-L43

### Python

    doc_ref = db.collection("users").document("alovelace")
    await doc_ref.set({"first": "Ada", "last": "Lovelace", "born": 1815})  
    https://github.com/GoogleCloudPlatform/python-docs-samples/blob/eff0040dee2bab9c4684f8425aa4d8ef28a9a244/firestore/cloud-async-client/snippets.py#L36-L37

##### C++

```c++
// Add a new document with a generated ID
Future<DocumentReference> user_ref =
    db->Collection("users").Add({{"first", FieldValue::String("Ada")},
                                 {"last", FieldValue::String("Lovelace")},
                                 {"born", FieldValue::Integer(1815)}});

user_ref.OnCompletion([](const Future<DocumentReference>& future) {
  if (future.error() == Error::kErrorOk) {
    std::cout << "DocumentSnapshot added with ID: " << future.result()->id()
              << std::endl;
  } else {
    std::cout << "Error adding document: " << future.error_message() << std::endl;
  }
});https://github.com/firebase/snippets-cpp/blob/778b6bcc8e8e8fcabb1c2e3a8d11ab51a26aa77b/firestore/android/FirestoreSnippetsCpp/app/src/main/cpp/snippets.cpp#L79-L92
```

##### Node.js

    const docRef = db.collection('users').doc('alovelace');

    await docRef.set({
      first: 'Ada',
      last: 'Lovelace',
      born: 1815
    });  
    https://github.com/firebase/snippets-node/blob/4738eab0d52a393e4e3027e7a6992fd6c892faf2/firestore/main/index.js#L86-L92

##### 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)
    }  
    https://github.com/GoogleCloudPlatform/golang-samples/blob/2c9f7d4fe3c1b465d5285d558992506b46e78fd7/firestore/firestore_quickstart/main.go#L58-L65

##### PHP

### PHP

For more on installing and creating aCloud Firestoreclient, refer to[Cloud FirestoreClient Libraries](https://firebase.google.com/firestore/docs/reference/libraries).  

    $docRef = $db->collection('samples/php/users')->document('alovelace');
    $docRef->set([
        'first' => 'Ada',
        'last' => 'Lovelace',
        'born' => 1815
    ]);
    printf('Added data to the lovelace document in the users collection.' . PHP_EOL);  
    https://github.com/GoogleCloudPlatform/php-docs-samples/blob/54369af5505ba98a554966e4f451819ec63cc74a/firestore/src/setup_dataset.php#L40-L46

##### Unity

```c#
DocumentReference docRef = db.Collection("users").Document("alovelace");
Dictionary<string, object> user = new Dictionary<string, object>
{
	{ "First", "Ada" },
	{ "Last", "Lovelace" },
	{ "Born", 1815 },
};
docRef.SetAsync(user).ContinueWithOnMainThread(task => {
	Debug.Log("Added data to the alovelace document in the users collection.");
});
```

##### 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);  
    https://github.com/GoogleCloudPlatform/dotnet-docs-samples/blob/7c95aa33b780cf05c9d699b3c664812d40629c35/firestore/api/Quickstart/Program.cs#L46-L53

##### Ruby

    doc_ref = firestore.doc "#{collection_path}/alovelace"

    doc_ref.set(
      {
        first: "Ada",
        last:  "Lovelace",
        born:  1815
      }
    )

    puts "Added data to the alovelace document in the users collection."  
    https://github.com/googleapis/google-cloud-ruby/blob/2248768197f89409e73f1161967200da9f77459a/google-cloud-firestore/samples/quickstart.rb#L36-L46

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

```javascript
// Add a second document with a generated ID.
import { addDoc, collection } from "firebase/firestore"; 

try {
  const docRef = await addDoc(collection(db, "users"), {
    first: "Alan",
    middle: "Mathison",
    last: "Turing",
    born: 1912
  });

  console.log("Document written with ID: ", docRef.id);
} catch (e) {
  console.error("Error adding document: ", e);
}https://github.com/firebase/snippets-web/blob/95c8c159ff4d90af442352f058406f1aeb8adcbb/snippets/firestore-next/test-firestore/add_alan_turing.js#L8-L22
```

### Web

[Learn more](https://firebase.google.com/docs/web/learn-more#modular-version)about the tree-shakeable modular Web API and its advantages over the namespaced API.  

```javascript
// Add a second document with a generated ID.
db.collection("users").add({
    first: "Alan",
    middle: "Mathison",
    last: "Turing",
    born: 1912
})
.then((docRef) => {
    console.log("Document written with ID: ", docRef.id);
})
.catch((error) => {
    console.error("Error adding document: ", error);
});https://github.com/firebase/snippets-web/blob/95c8c159ff4d90af442352f058406f1aeb8adcbb/firestore/test.firestore.js#L155-L167
```

##### Swift

**Note:**This product is not available on watchOS and App Clip targets.  

```swift
// Add a second document with a generated ID.
do {
  let ref = try await db.collection("users").addDocument(data: [
    "first": "Alan",
    "middle": "Mathison",
    "last": "Turing",
    "born": 1912
  ])
  print("Document added with ID: \(ref.documentID)")
} catch {
  print("Error adding document: \(error)")
}https://github.com/firebase/snippets-ios/blob/6b288cfa45a67c92c5db32953f028f8ed9e5a81b/firestore/swift/firestore-smoketest/ViewController.swift#L188-L199
```

##### Objective-C

**Note:**This product is not available on watchOS and App Clip targets.  

```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);
      }
    }];https://github.com/firebase/snippets-ios/blob/6b288cfa45a67c92c5db32953f028f8ed9e5a81b/firestore/objc/firestore-smoketest-objc/ViewController.m#L110-L123
```

### Kotlin

```kotlin
// 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)
    }https://github.com/firebase/snippets-android/blob/294e0edf389e04ad85622081afb988aed37c20fb/firestore/app/src/main/java/com/google/example/firestore/kotlin/DocSnippets.kt#L158-L174
```

### Java

```java
// 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);
            }
        });https://github.com/firebase/snippets-android/blob/294e0edf389e04ad85622081afb988aed37c20fb/firestore/app/src/main/java/com/google/example/firestore/DocSnippets.java#L190-L211
```

### Dart

```dart
// Create a new user with a first and last name
final user = <String, dynamic>{
  "first": "Alan",
  "middle": "Mathison",
  "last": "Turing",
  "born": 1912
};

// Add a new document with a generated ID
db.collection("users").add(user).then((DocumentReference doc) =>
    print('DocumentSnapshot added with ID: ${doc.id}'));https://github.com/firebase/snippets-flutter/blob/f674af111fe63779c39e79699f7d269231f77563/packages/firebase_snippets_app/lib/snippets/firestore.dart#L59-L69
```

##### 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());  
    https://github.com/googleapis/java-firestore/blob/fa478387d1cefe1ec0909cd37fb28e0b5ec97e63/samples/snippets/src/main/java/com/example/firestore/Quickstart.java#L100-L109

##### Python

    doc_ref = db.collection("users").document("aturing")
    doc_ref.set({"first": "Alan", "middle": "Mathison", "last": "Turing", "born": 1912})  
    https://github.com/GoogleCloudPlatform/python-docs-samples/blob/eff0040dee2bab9c4684f8425aa4d8ef28a9a244/firestore/cloud-client/snippets.py#L50-L51

### Python

    doc_ref = db.collection("users").document("aturing")
    await doc_ref.set(
        {"first": "Alan", "middle": "Mathison", "last": "Turing", "born": 1912}
    )  
    https://github.com/GoogleCloudPlatform/python-docs-samples/blob/eff0040dee2bab9c4684f8425aa4d8ef28a9a244/firestore/cloud-async-client/snippets.py#L44-L47

##### C++

```c++
db->Collection("users")
    .Add({{"first", FieldValue::String("Alan")},
          {"middle", FieldValue::String("Mathison")},
          {"last", FieldValue::String("Turing")},
          {"born", FieldValue::Integer(1912)}})
    .OnCompletion([](const Future<DocumentReference>& future) {
      if (future.error() == Error::kErrorOk) {
        std::cout << "DocumentSnapshot added with ID: "
                  << future.result()->id() << std::endl;
      } else {
        std::cout << "Error adding document: " << future.error_message()
                  << std::endl;
      }
    });https://github.com/firebase/snippets-cpp/blob/778b6bcc8e8e8fcabb1c2e3a8d11ab51a26aa77b/firestore/android/FirestoreSnippetsCpp/app/src/main/cpp/snippets.cpp#L101-L114
```

##### Node.js

    const aTuringRef = db.collection('users').doc('aturing');

    await aTuringRef.set({
      'first': 'Alan',
      'middle': 'Mathison',
      'last': 'Turing',
      'born': 1912
    });  
    https://github.com/firebase/snippets-node/blob/4738eab0d52a393e4e3027e7a6992fd6c892faf2/firestore/main/index.js#L96-L103

##### 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)
    }  
    https://github.com/GoogleCloudPlatform/golang-samples/blob/2c9f7d4fe3c1b465d5285d558992506b46e78fd7/firestore/firestore_quickstart/main.go#L69-L77

##### PHP

### PHP

For more on installing and creating aCloud Firestoreclient, refer to[Cloud FirestoreClient Libraries](https://firebase.google.com/firestore/docs/reference/libraries).  

    $docRef = $db->collection('samples/php/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);  
    https://github.com/GoogleCloudPlatform/php-docs-samples/blob/54369af5505ba98a554966e4f451819ec63cc74a/firestore/src/setup_dataset.php#L49-L56

##### Unity

```c#
DocumentReference docRef = db.Collection("users").Document("aturing");
Dictionary<string, object> user = new Dictionary<string, object>
{
	{ "First", "Alan" },
	{ "Middle", "Mathison" },
	{ "Last", "Turing" },
	{ "Born", 1912 }
};
docRef.SetAsync(user).ContinueWithOnMainThread(task => {
	Debug.Log("Added data to the aturing document in the users collection.");
});
```

##### 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);  
    https://github.com/GoogleCloudPlatform/dotnet-docs-samples/blob/7c95aa33b780cf05c9d699b3c664812d40629c35/firestore/api/Quickstart/Program.cs#L62-L70

##### Ruby

    doc_ref = firestore.doc "#{collection_path}/aturing"

    doc_ref.set(
      {
        first:  "Alan",
        middle: "Mathison",
        last:   "Turing",
        born:   1912
      }
    )

    puts "Added data to the aturing document in the users collection."  
    https://github.com/googleapis/google-cloud-ruby/blob/2248768197f89409e73f1161967200da9f77459a/google-cloud-firestore/samples/quickstart.rb#L56-L67

## Read data

Use the data viewer in the[Firebase console](https://console.firebase.google.com/project/_/firestore/data)to quickly verify that you've added data toCloud Firestore.

You can also use the "get" method to retrieve the entire collection.  

### Web

```javascript
import { collection, getDocs } from "firebase/firestore"; 

const querySnapshot = await getDocs(collection(db, "users"));
querySnapshot.forEach((doc) => {
  console.log(`${doc.id} => ${doc.data()}`);
});https://github.com/firebase/snippets-web/blob/95c8c159ff4d90af442352f058406f1aeb8adcbb/snippets/firestore-next/test-firestore/get_all_users.js#L8-L13
```

### Web

[Learn more](https://firebase.google.com/docs/web/learn-more#modular-version)about the tree-shakeable modular Web API and its advantages over the namespaced API.  

```javascript
db.collection("users").get().then((querySnapshot) => {
    querySnapshot.forEach((doc) => {
        console.log(`${doc.id} => ${doc.data()}`);
    });
});https://github.com/firebase/snippets-web/blob/95c8c159ff4d90af442352f058406f1aeb8adcbb/firestore/test.firestore.js#L143-L147
```

##### Swift

**Note:**This product is not available on watchOS and App Clip targets.  

```swift
do {
  let snapshot = try await db.collection("users").getDocuments()
  for document in snapshot.documents {
    print("\(document.documentID) => \(document.data())")
  }
} catch {
  print("Error getting documents: \(error)")
}https://github.com/firebase/snippets-ios/blob/6b288cfa45a67c92c5db32953f028f8ed9e5a81b/firestore/swift/firestore-smoketest/ViewController.swift#L205-L212
```

##### Objective-C

**Note:**This product is not available on watchOS and App Clip targets.  

```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);
        }
      }
    }];https://github.com/firebase/snippets-ios/blob/6b288cfa45a67c92c5db32953f028f8ed9e5a81b/firestore/objc/firestore-smoketest-objc/ViewController.m#L129-L139
```

### Kotlin

```kotlin
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)
    }https://github.com/firebase/snippets-android/blob/294e0edf389e04ad85622081afb988aed37c20fb/firestore/app/src/main/java/com/google/example/firestore/kotlin/DocSnippets.kt#L180-L189
```

### Java

```java
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());
                }
            }
        });https://github.com/firebase/snippets-android/blob/294e0edf389e04ad85622081afb988aed37c20fb/firestore/app/src/main/java/com/google/example/firestore/DocSnippets.java#L217-L230
```

### Dart

```dart
await db.collection("users").get().then((event) {
  for (var doc in event.docs) {
    print("${doc.id} => ${doc.data()}");
  }
});https://github.com/firebase/snippets-flutter/blob/f674af111fe63779c39e79699f7d269231f77563/packages/firebase_snippets_app/lib/snippets/firestore.dart#L75-L79
```

##### 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"));
    }  
    https://github.com/googleapis/java-firestore/blob/fa478387d1cefe1ec0909cd37fb28e0b5ec97e63/samples/snippets/src/main/java/com/example/firestore/Quickstart.java#L152-L166

##### Python

```python
users_ref = db.collection("users")
docs = users_ref.stream()

for doc in docs:
    print(f"{doc.id} => {doc.to_dict()}")https://github.com/GoogleCloudPlatform/python-docs-samples/blob/eff0040dee2bab9c4684f8425aa4d8ef28a9a244/firestore/cloud-client/snippets.py#L58-L62
```

### Python

    users_ref = db.collection("users")
    docs = users_ref.stream()

    async for doc in docs:
        print(f"{doc.id} => {doc.to_dict()}")  
    https://github.com/GoogleCloudPlatform/python-docs-samples/blob/eff0040dee2bab9c4684f8425aa4d8ef28a9a244/firestore/cloud-async-client/snippets.py#L54-L58

##### C++

```c++
Future<QuerySnapshot> users = db->Collection("users").Get();
users.OnCompletion([](const Future<QuerySnapshot>& future) {
  if (future.error() == Error::kErrorOk) {
    for (const DocumentSnapshot& document : future.result()->documents()) {
      std::cout << document << std::endl;
    }
  } else {
    std::cout << "Error getting documents: " << future.error_message()
              << std::endl;
  }
});https://github.com/firebase/snippets-cpp/blob/778b6bcc8e8e8fcabb1c2e3a8d11ab51a26aa77b/firestore/android/FirestoreSnippetsCpp/app/src/main/cpp/snippets.cpp#L131-L141
```

##### Node.js

    const snapshot = await db.collection('users').get();
    snapshot.forEach((doc) => {
      console.log(doc.id, '=>', doc.data());
    });  
    https://github.com/firebase/snippets-node/blob/4738eab0d52a393e4e3027e7a6992fd6c892faf2/firestore/main/index.js#L119-L122

##### 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())
    }  
    https://github.com/GoogleCloudPlatform/golang-samples/blob/2c9f7d4fe3c1b465d5285d558992506b46e78fd7/firestore/firestore_quickstart/main.go#L81-L91

##### PHP

### PHP

For more on installing and creating aCloud Firestoreclient, refer to[Cloud FirestoreClient Libraries](https://firebase.google.com/firestore/docs/reference/libraries).  

    $usersRef = $db->collection('samples/php/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);  
    https://github.com/GoogleCloudPlatform/php-docs-samples/blob/54369af5505ba98a554966e4f451819ec63cc74a/firestore/src/setup_dataset_read.php#L40-L52

##### Unity

```c#
CollectionReference usersRef = db.Collection("users");
usersRef.GetSnapshotAsync().ContinueWithOnMainThread(task =>
{
  QuerySnapshot snapshot = task.Result;
  foreach (DocumentSnapshot document in snapshot.Documents)
  {
    Debug.Log(String.Format("User: {0}", document.Id));
    Dictionary<string, object> documentDictionary = document.ToDictionary();
    Debug.Log(String.Format("First: {0}", documentDictionary["First"]));
    if (documentDictionary.ContainsKey("Middle"))
    {
      Debug.Log(String.Format("Middle: {0}", documentDictionary["Middle"]));
    }

    Debug.Log(String.Format("Last: {0}", documentDictionary["Last"]));
    Debug.Log(String.Format("Born: {0}", documentDictionary["Born"]));
  }

  Debug.Log("Read all data from the users collection.");
});
```

##### 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();
    }  
    https://github.com/GoogleCloudPlatform/dotnet-docs-samples/blob/7c95aa33b780cf05c9d699b3c664812d40629c35/firestore/api/Quickstart/Program.cs#L79-L93

##### Ruby

    users_ref = firestore.col collection_path
    users_ref.get do |user|
      puts "#{user.document_id} data: #{user.data}."
    end  
    https://github.com/googleapis/google-cloud-ruby/blob/2248768197f89409e73f1161967200da9f77459a/google-cloud-firestore/samples/quickstart.rb#L77-L80

## Secure your data

If you're using the web, Android, or Apple platforms SDK, use[Firebase Authentication](https://firebase.google.com/docs/auth/)and[Cloud FirestoreSecurity Rules](https://firebase.google.com/docs/firestore/security/get-started)to secure your data inCloud Firestore.

Here are some basic rule sets you can use to get started. You can modify your security rules in the[**Rules tab**](https://console.firebase.google.com/project/_/firestore/rules)of the console.  

### Auth required

    // Allow read/write access to a document keyed by the user's UID
    service cloud.firestore {
      match /databases/{database}/documents {
        match /users/{uid} {
          allow read, write: if request.auth != null && request.auth.uid == uid;
        }
      }
    }

### Production 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;
        }
      }
    }

Before you deploy your web, Android, or iOS app to production, also take steps to ensure that only your app clients can access yourCloud Firestoredata. See the[App Check](https://firebase.google.com/docs/app-check)documentation.

If you're using one of the server SDKs, use[Identity and Access Management (IAM)](https://cloud.google.com/firestore/docs/security/iam)to secure your data inCloud Firestore.

## Watch a video tutorial

For detailed guidance on getting started with theCloud Firestoremobile client libraries, watch one of the following video tutorials:  

##### Web

##### iOS+

##### Android

You can find more videos in the Firebase[YouTube channel](https://www.youtube.com/firebase).

## Next steps

Deepen your knowledge with the following topics:

- **Codelabs** --- Learn to useCloud Firestorein a real app by following the codelab for[Android](https://codelabs.developers.google.com/codelabs/firestore-android),[iOS](https://codelabs.developers.google.com/codelabs/firestore-ios), or[web](https://codelabs.developers.google.com/codelabs/firestore-web).
- **[Data model](https://firebase.google.com/docs/firestore/data-model)** --- Learn more about how data is structured inCloud Firestore, including hierarchical data and subcollections.
- **[Add data](https://firebase.google.com/docs/firestore/manage-data/add-data)** --- Learn more about creating and updating data inCloud Firestore.
- **[Get data](https://firebase.google.com/docs/firestore/query-data/get-data)**--- Learn more about how to retrieve data.
- **[Perform simple and compound queries](https://firebase.google.com/docs/firestore/query-data/queries)**--- Learn how to run simple and compound queries.
- **[Order and limit queries](https://firebase.google.com/docs/firestore/query-data/order-limit-data)**Learn how to order and limit the data returned by your queries.