Cloud Firestore 入門

本快速入門向您展示如何設定 Cloud Firestore、新增數據,然後在 Firebase 控制台中查看剛剛新增的數據。

建立 Cloud Firestore 資料庫

  1. 如果您尚未建立 Firebase 項目,請在Firebase 控制台中點擊新增項目,然後按照螢幕上的指示建立 Firebase 項目或將 Firebase 服務新增至現有 GCP 項目。

  2. 導覽至Firebase 控制台Cloud Firestore部分。系統會提示您選擇現有的 Firebase 專案。遵循資料庫建立工作流程。

  3. 選擇 Cloud Firestore 安全性法則的啟動模式:

    測試模式

    適合開始使用行動和 Web 用戶端庫,但允許任何人讀取和覆蓋您的資料。測試後,請務必查看「保護您的資料」部分。

    若要開始使用 Web、Apple 平台或 Android SDK,請選擇測試模式。

    鎖定模式

    拒絕來自行動和 Web 用戶端的所有讀取和寫入。經過驗證的應用程式伺服器(C#、Go、Java、Node.js、PHP、Python 或 Ruby)仍然可以存取您的資料庫。

    若要開始使用 C#、Go、Java、Node.js、PHP、Python 或 Ruby 伺服器用戶端程式庫,請選擇鎖定模式。

    您的初始 Cloud Firestore 安全性規則集將套用至您的預設 Cloud Firestore 資料庫。如果您為專案建立多個資料庫,則可以為每個資料庫部署 Cloud Firestore 安全性規則。

  4. 選擇資料庫的位置

    • 此位置設定是您專案的預設 Google Cloud Platform (GCP) 資源位置。請注意,此位置將用於專案中需要位置設定的 GCP 服務,特別是您的預設Cloud Storage儲存桶和App Engine應用程式(如果您使用 Cloud Scheduler,則需要)。

    • 如果您無法選擇位置,則您的專案已有預設 GCP 資源位置。它是在專案建立期間或設定另一個需要位置設定的服務時設定的。

  5. 按一下“完成”

啟用 Cloud Firestore 時,也會啟用Cloud API Manager中的 API。

設定您的開發環境

將所需的依賴項和用戶端程式庫新增至您的應用程式。

Web namespaced API

  1. 按照說明將Firebase 新增到您的 Web 應用程式
  2. 將 Firebase 和 Cloud Firestore 庫新增到您的應用程式中:
    <script src="https://www.gstatic.com/firebasejs/10.9.0/firebase-app-compat.js"></script>
    <script src="https://www.gstatic.com/firebasejs/10.9.0/firebase-firestore-compat.js"></script>
    Cloud Firestore SDK 也可以作為 npm 套件提供。
    npm install firebase@10.9.0 --save
    
    您需要手動要求 Firebase 和 Cloud Firestore。
    import firebase from "firebase/compat/app";
    // Required for side-effects
    import "firebase/firestore";
    

Web modular API

  1. 按照說明將Firebase 新增到您的 Web 應用程式
  2. Cloud Firestore SDK 以 npm 套件的形式提供。
    npm install firebase@10.9.0 --save
    
    您需要匯入 Firebase 和 Cloud Firestore。
    import { initializeApp } from "firebase/app";
    import { getFirestore } from "firebase/firestore";
    
iOS+

按照說明將Firebase 新增到您的 Apple 應用程式

使用 Swift Package Manager 安裝和管理 Firebase 相依性。

  1. 在 Xcode 中,開啟應用程式項目,導覽至File > Swift Packages > Add Package Dependency
  2. 出現提示時,新增 Firebase Apple 平台 SDK 儲存庫:
  3.   https://github.com/firebase/firebase-ios-sdk
      
  4. 選擇 Firestore 庫。
  5. 完成後,Xcode 將自動開始在背景解析並下載您的依賴項。
安卓
  1. 按照說明將Firebase 新增到您的 Android 應用程式
  2. 使用Firebase Android BoM ,在模組(應用程式級)Gradle 檔案(通常app/build.gradle.ktsapp/build.gradle )中聲明適用於 Android 的 Cloud Firestore 程式庫的依賴項。
    dependencies {
        // Import the BoM for the Firebase platform
        implementation(platform("com.google.firebase:firebase-bom:32.7.4"))
    
        // 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")
    }
    

    透過使用Firebase Android BoM ,您的應用程式將始終使用 Firebase Android 程式庫的相容版本。

    (替代方法)在不使用 BoM 的情況下聲明 Firebase 庫依賴項

    如果您選擇不使用 Firebase BoM,則必須在其依賴項行中指定每個 Firebase 庫版本。

    請注意,如果您在應用程式中使用多個Firebase 程式庫,我們強烈建議使用 BoM 來管理程式庫版本,這可確保所有版本相容。

    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:24.10.3")
    }
    

    正在尋找 Kotlin 特定的庫模組?2023 年 10 月版本開始,Kotlin 和 Java 開發人員都可以依賴主庫模組(有關詳細信息,請參閱有關此計劃的常見問題解答)。

Dart

  1. 如果您還沒準備好,請在 Flutter 應用程式中設定並初始化 Firebase
  2. 從 Flutter 專案的根目錄中,執行以下命令來安裝外掛程式:
    flutter pub add cloud_firestore
  3. 完成後,重建您的 Flutter 應用程式:
    flutter run
  4. 可選:透過包含預編譯框架來縮短 iOS 和 macOS 的建置時間。

    目前,適用於 iOS 的 Firestore SDK 依賴於在 Xcode 中建立可能需要 5 分鐘以上的程式碼。若要顯著縮短建置時間,您可以透過將此行新增至 Podfile 中的target 'Runner' do區塊來使用預編譯版本:

    target 'Runner' do
      use_frameworks!
      use_modular_headers!
    
      pod 'FirebaseFirestore',
        :git => 'https://github.com/invertase/firestore-ios-sdk-frameworks.git',
        :tag => 'IOS_SDK_VERSION'
    
      flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))
      target 'RunnerTests' do
        inherit! :search_paths
      end
    end

    IOS_SDK_VERSION替換為firebase_corefirebase_sdk_version.rb檔案中指定的 Firebase iOS SDK 版本。如果您沒有使用最新版本的firebase_core ,請在本機 Pub 套件快取(通常~/.pub-cache )中尋找此檔案。

    此外,請確保您已將 CocoaPods 升級至 1.9.1 或更高版本:

    gem install cocoapods

    有關更多信息,請參閱GitHub 上的問題

爪哇
  1. 將 Firebase Admin SDK 新增到您的應用程式:
    • 使用 Gradle:
      compile 'com.google.firebase:firebase-admin:1.32.0'
      
    • 使用 Maven:
      <dependency>
        <groupId>com.google.firebase</groupId>
        <artifactId>firebase-admin</artifactId>
        <version>1.32.0</version>
      </dependency>
           
  2. 請依照以下說明,使用您環境中的正確憑證初始化 Cloud Firestore。
Python
  1. 將 Firebase Admin SDK 新增到您的 Python 應用程式:
    pip install --upgrade firebase-admin
  2. 請依照以下說明,使用您環境中的正確憑證初始化 Cloud Firestore。
C++
  1. 按照說明將Firebase 新增到您的 C++ 專案
  2. Android 的 C++ 介面。
    • 漸變依賴項。將以下內容新增至您的模組(應用程式層級)Gradle 檔案(通常app/build.gradle ):
              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
              }
              
    • 二進制依賴關係。同樣,取得二進位依賴項的建議方法是將以下內容新增至CMakeLists.txt檔案:
              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. 若要設定桌面集成,請參閱將 Firebase 新增至您的 C++ 專案
統一
  1. 按照說明將Firebase 新增到您的 Unity 專案
  2. 使用 Unity 介面配置您的專案以縮小 Android 建置。
  3. 您必須縮小建置以避免出現Error while merging dex archives訊息。

    • 該選項可以在Player Settings > Android > Publishing Settings > Minify中找到。
    • 不同版本的 Unity 中的選項可能有所不同,因此請參閱官方Unity 文件Firebase Unity 建置偵錯指南
    • 如果啟用縮小後,引用的方法數量仍然超過限制,另一個選擇是啟用multidex
      • mainTemplate.gradle如果啟用了播放器設定下的自訂 Gradle 模板
      • 或者,如果您使用 Android Studio 建置匯出的項目,則為模組級build.gradle檔案。
Node.js
  1. 將 Firebase Admin SDK 新增至您的應用程式:
    npm install firebase-admin --save
  2. 請依照以下說明,使用您環境中的正確憑證初始化 Cloud Firestore。
  1. 將 Firebase Admin SDK 新增至您的 Go 應用程式:
    go get firebase.google.com/go
    
  2. 請依照以下說明,使用您環境中的正確憑證初始化 Cloud Firestore。
PHP
  1. Cloud Firestore 伺服器用戶端程式庫(Java、Node.js、Python、Go、PHP、C# 和 Ruby)使用Google 應用程式預設憑證進行驗證。
    • 若要從開發環境進行驗證,請將GOOGLE_APPLICATION_CREDENTIALS環境變數設定為指向 JSON 服務帳戶金鑰檔案。您可以在API控制台憑證頁面建立金鑰檔案。
      export GOOGLE_APPLICATION_CREDENTIALS="path/to/your/keyfile.json"
    • 在生產環境中,如果您使用與 Cloud Firestore 相同的專案在 App Engine 或 Compute Engine 上執行應用程序,則無需進行身份驗證。否則,請設定一個服務帳戶
  2. 安裝並啟用 PHP 的gRPC 擴展,您將需要使用客戶端程式庫。
  3. 將 Cloud Firestore PHP 函式庫新增至您的應用程式:
    composer require google/cloud-firestore
C#
  1. Cloud Firestore 伺服器用戶端程式庫(Java、Node.js、Python、Go、PHP、C# 和 Ruby)使用Google 應用程式預設憑證進行驗證。
    • 若要從開發環境進行驗證,請將GOOGLE_APPLICATION_CREDENTIALS環境變數設定為指向 JSON 服務帳戶金鑰檔案。您可以在API控制台憑證頁面建立金鑰檔案。
      export GOOGLE_APPLICATION_CREDENTIALS="path/to/your/keyfile.json"
    • 在生產環境中,如果您使用與 Cloud Firestore 相同的專案在 App Engine 或 Compute Engine 上執行應用程序,則無需進行身份驗證。否則,請設定一個服務帳戶
  2. 將 Cloud Firestore C# 程式庫新增至應用程式的.csproj檔案:
    <ItemGroup>
      <PackageReference Include="Google.Cloud.Firestore" Version="1.1.0-beta01" />
    </ItemGroup>
  3. 將以下內容新增至您的Program.cs檔案:
    using Google.Cloud.Firestore;
紅寶石
  1. Cloud Firestore 伺服器用戶端程式庫(Java、Node.js、Python、Go、PHP、C# 和 Ruby)使用Google 應用程式預設憑證進行驗證。
    • 若要從開發環境進行驗證,請將GOOGLE_APPLICATION_CREDENTIALS環境變數設定為指向 JSON 服務帳戶金鑰檔案。您可以在API控制台憑證頁面建立金鑰檔案。
      export GOOGLE_APPLICATION_CREDENTIALS="path/to/your/keyfile.json"
    • 在生產環境中,如果您使用與 Cloud Firestore 相同的專案在 App Engine 或 Compute Engine 上執行應用程序,則無需進行身份驗證。否則,請設定一個服務帳戶
  2. 將 Cloud Firestore Ruby 庫新增到您的應用程式的Gemfile中:
    gem "google-cloud-firestore"
  3. 使用下列指令從Gemfile安裝依賴項:
    bundle install

(可選)使用 Firebase 本機模擬器套件進行原型設計和測試

對於行動開發人員,在討論應用如何寫入 Cloud Firestore 和從 Cloud Firestore 讀取之前,我們先介紹一組可用於原型設計和測試 Cloud Firestore 功能的工具:Firebase Local Emulator Suite。如果您正在嘗試不同的資料模型、優化安全規則或努力尋找與後端互動的最具成本效益的方式,那麼能夠在本地工作而不部署即時服務可能是一個好主意。

Cloud Firestore 模擬器是本機模擬器套件的一部分,它使您的應用程式能夠與模擬的資料庫內容和配置以及可選的模擬專案資源(函數、其他資料庫和安全規則)進行互動。

使用 Cloud Firestore 模擬器只需幾個步驟:

  1. 將一行程式碼新增至應用程式的測試配置以連接到模擬器。
  2. 從本地專案目錄的根目錄中,運行firebase emulators:start
  3. 像往常一樣使用 Cloud Firestore 平台 SDK 從應用的原型程式碼進行呼叫。

提供了涉及 Cloud Firestore 和 Cloud Functions 的詳細演練。您還應該看看本地仿真器套件的介紹

初始化 Cloud Firestore

初始化 Cloud Firestore 執行個體:

Web modular API

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

FIREBASE_CONFIGURATION替換為您的網頁應用程式的firebaseConfig

若要在裝置失去連線時保留數據,請參閱啟用離線資料文件。

Web namespaced API

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

FIREBASE_CONFIGURATION替換為您的網頁應用程式的firebaseConfig

若要在裝置失去連線時保留數據,請參閱啟用離線資料文件。

迅速
注意:此產品不適用於 watchOS 和 App Clip 目標。
import FirebaseCore
import FirebaseFirestore
FirebaseApp.configure()

let db = Firestore.firestore()
Objective-C
注意:此產品不適用於 watchOS 和 App Clip 目標。
@import FirebaseCore;
@import FirebaseFirestore;

// Use Firebase library to configure APIs
[FIRApp configure];
  
FIRFirestore *defaultFirestore = [FIRFirestore firestore];

Kotlin+KTX

// Access a Cloud Firestore instance from your Activity
val db = Firebase.firestore

Java

// Access a Cloud Firestore instance from your Activity
FirebaseFirestore db = FirebaseFirestore.getInstance();

Dart

db = FirebaseFirestore.instance;
爪哇
Cloud Firestore SDK 根據您的環境以不同的方式初始化。以下是最常見的方法。有關完整參考,請參閱初始化 Admin SDK
  • 在 Google Cloud
    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();
    
    上初始化
  • 在自己的伺服器上初始化

    若要在您自己的伺服器上使用 Firebase Admin SDK,請使用服務帳號

    前往 Google Cloud 控制台中的IAM 和管理 > 服務帳號。產生新的私鑰並保存 JSON 檔案。然後使用該檔案初始化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
    Cloud Firestore SDK 根據您的環境以不同的方式初始化。以下是最常見的方法。有關完整參考,請參閱初始化 Admin SDK
  • 在 Google Cloud
    import firebase_admin
    from firebase_admin import firestore
    
    # Application Default credentials are automatically created.
    app = firebase_admin.initialize_app()
    db = firestore.client()
    上初始化

    現有的應用程式預設憑證也可用於初始化 SDK。

    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()
  • 在自己的伺服器上初始化

    若要在您自己的伺服器上使用 Firebase Admin SDK,請使用服務帳號

    前往 Google Cloud 控制台中的IAM 和管理 > 服務帳號。產生新的私鑰並保存 JSON 檔案。然後使用該檔案初始化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')
    
    app = firebase_admin.initialize_app(cred)
    
    db = firestore.client()
  • Python

    Cloud Firestore SDK 根據您的環境以不同的方式初始化。以下是最常見的方法。有關完整參考,請參閱初始化 Admin SDK
  • 在 Google Cloud
    import firebase_admin
    from firebase_admin import firestore_async
    
    # Application Default credentials are automatically created.
    app = firebase_admin.initialize_app()
    db = firestore_async.client()
    上初始化

    現有的應用程式預設憑證也可用於初始化 SDK。

    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()
  • 在自己的伺服器上初始化

    若要在您自己的伺服器上使用 Firebase Admin SDK,請使用服務帳號

    前往 Google Cloud 控制台中的IAM 和管理 > 服務帳號。產生新的私鑰並保存 JSON 檔案。然後使用該檔案初始化SDK:

    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()
  • C++
    // Make sure the call to `Create()` happens some time before you call Firestore::GetInstance().
    App::Create();
    Firestore* db = Firestore::GetInstance();
    Node.js
    Cloud Firestore SDK 根據您的環境以不同的方式初始化。以下是最常見的方法。有關完整參考,請參閱初始化 Admin SDK
    • 在 Cloud Functions 上初始化
      const { initializeApp, applicationDefault, cert } = require('firebase-admin/app');
      const { getFirestore, Timestamp, FieldValue, Filter } = require('firebase-admin/firestore');
      initializeApp();
      
      const db = getFirestore();
      
    • 在 Google Cloud 上初始化
      const { initializeApp, applicationDefault, cert } = require('firebase-admin/app');
      const { getFirestore, Timestamp, FieldValue, Filter } = require('firebase-admin/firestore');
      initializeApp({
        credential: applicationDefault()
      });
      
      const db = getFirestore();
    • 在自己的伺服器上初始化

      若要在您自己的伺服器(或任何其他 Node.js 環境)上使用 Firebase Admin SDK,請使用服務帳戶。前往 Google Cloud 控制台中的IAM 和管理 > 服務帳號。產生新的私鑰並保存 JSON 檔案。然後使用該檔案初始化SDK:

      const { initializeApp, applicationDefault, cert } = require('firebase-admin/app');
      const { getFirestore, Timestamp, FieldValue, Filter } = require('firebase-admin/firestore');
      const serviceAccount = require('./path/to/serviceAccountKey.json');
      
      initializeApp({
        credential: cert(serviceAccount)
      });
      
      const db = getFirestore();
      
    Cloud Firestore SDK 根據您的環境以不同的方式初始化。以下是最常見的方法。有關完整參考,請參閱初始化 Admin SDK
  • 在 Google Cloud
    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()
    
    上初始化
  • 在自己的伺服器上初始化

    若要在您自己的伺服器上使用 Firebase Admin SDK,請使用服務帳號

    前往 Google Cloud 控制台中的IAM 和管理 > 服務帳號。產生新的私鑰並保存 JSON 檔案。然後使用該檔案初始化SDK:

    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

    有關安裝和建立 Cloud Firestore 用戶端的更多信息,請參閱Cloud Firestore 用戶端程式庫

    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);
        }
    }
    統一
    using Firebase.Firestore;
    using Firebase.Extensions;
    FirebaseFirestore db = FirebaseFirestore.DefaultInstance;
    C#

    C#

    有關安裝和建立 Cloud Firestore 用戶端的更多信息,請參閱Cloud Firestore 用戶端程式庫

    FirestoreDb db = FirestoreDb.Create(project);
    Console.WriteLine("Created Cloud Firestore client with project ID: {0}", project);
    紅寶石
    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."

    新增數據

    Cloud Firestore 將資料儲存在文件中,文件儲存在集合中。當您第一次將資料新增至文件時,Cloud Firestore 會隱含地建立集合和文件。您不需要明確建立集合或文件。

    使用以下範例程式碼建立新集合和文件。

    Web modular API

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

    Web namespaced API

    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);
    });
    迅速
    注意:此產品不適用於 watchOS 和 App Clip 目標。
    // 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)")
    }
    Objective-C
    注意:此產品不適用於 watchOS 和 App Clip 目標。
    // 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);
          }
        }];

    Kotlin+KTX

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

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

    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}'));
    爪哇
    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("users").document("alovelace")
    doc_ref.set({"first": "Ada", "last": "Lovelace", "born": 1815})

    Python

    doc_ref = db.collection("users").document("alovelace")
    await doc_ref.set({"first": "Ada", "last": "Lovelace", "born": 1815})
    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;
      }
    });
    Node.js
    const docRef = db.collection('users').doc('alovelace');
    
    await docRef.set({
      first: 'Ada',
      last: 'Lovelace',
      born: 1815
    });
    _, _, 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)
    }
    PHP

    PHP

    有關安裝和建立 Cloud Firestore 用戶端的更多信息,請參閱Cloud Firestore 用戶端程式庫

    $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);
    統一
    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);
    紅寶石
    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."

    現在將另一個文件新增至users集合。請注意,此文件包含一個未出現在第一個文件中的鍵值對(中間名)。集合中的文件可以包含不同的資訊集。

    Web modular API

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

    Web namespaced API

    // 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);
    });
    迅速
    注意:此產品不適用於 watchOS 和 App Clip 目標。
    // 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)")
    }
    Objective-C
    注意:此產品不適用於 watchOS 和 App Clip 目標。
    // 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);
          }
        }];

    Kotlin+KTX

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

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

    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}'));
    爪哇
    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("users").document("aturing")
    doc_ref.set({"first": "Alan", "middle": "Mathison", "last": "Turing", "born": 1912})

    Python

    doc_ref = db.collection("users").document("aturing")
    await doc_ref.set(
        {"first": "Alan", "middle": "Mathison", "last": "Turing", "born": 1912}
    )
    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;
          }
        });
    Node.js
    const aTuringRef = db.collection('users').doc('aturing');
    
    await aTuringRef.set({
      'first': 'Alan',
      'middle': 'Mathison',
      'last': 'Turing',
      'born': 1912
    });
    _, _, 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)
    }
    PHP

    PHP

    有關安裝和建立 Cloud Firestore 用戶端的更多信息,請參閱Cloud Firestore 用戶端程式庫

    $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);
    統一
    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);
    紅寶石
    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."

    讀取數據

    使用Firebase 控制台中的資料檢視器快速驗證您是否已將資料新增至 Cloud Firestore。

    您也可以使用“get”方法來檢索整個集合。

    Web modular API

    import { collection, getDocs } from "firebase/firestore"; 
    
    const querySnapshot = await getDocs(collection(db, "users"));
    querySnapshot.forEach((doc) => {
      console.log(`${doc.id} => ${doc.data()}`);
    });

    Web namespaced API

    db.collection("users").get().then((querySnapshot) => {
        querySnapshot.forEach((doc) => {
            console.log(`${doc.id} => ${doc.data()}`);
        });
    });
    迅速
    注意:此產品不適用於 watchOS 和 App Clip 目標。
    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)")
    }
    Objective-C
    注意:此產品不適用於 watchOS 和 App Clip 目標。
    [[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);
            }
          }
        }];

    Kotlin+KTX

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

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

    Dart

    await db.collection("users").get().then((event) {
      for (var doc in event.docs) {
        print("${doc.id} => ${doc.data()}");
      }
    });
    爪哇
    // asynchronously retrieve all users
    ApiFuture<QuerySnapshot> query = db.collection("users").get();
    // ...
    // query.get() blocks on response
    QuerySnapshot querySnapshot = query.get();
    List<QueryDocumentSnapshot> documents = querySnapshot.getDocuments();
    for (QueryDocumentSnapshot document : documents) {
      System.out.println("User: " + document.getId());
      System.out.println("First: " + document.getString("first"));
      if (document.contains("middle")) {
        System.out.println("Middle: " + document.getString("middle"));
      }
      System.out.println("Last: " + document.getString("last"));
      System.out.println("Born: " + document.getLong("born"));
    }
    Python
    users_ref = db.collection("users")
    docs = users_ref.stream()
    
    for doc in docs:
        print(f"{doc.id} => {doc.to_dict()}")

    Python

    users_ref = db.collection("users")
    docs = users_ref.stream()
    
    async for doc in docs:
        print(f"{doc.id} => {doc.to_dict()}")
    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;
      }
    });
    Node.js
    const snapshot = await db.collection('users').get();
    snapshot.forEach((doc) => {
      console.log(doc.id, '=>', doc.data());
    });
    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())
    }
    PHP

    PHP

    有關安裝和建立 Cloud Firestore 用戶端的更多信息,請參閱Cloud Firestore 用戶端程式庫

    $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);
    統一
    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();
    }
    紅寶石
    users_ref = firestore.col collection_path
    users_ref.get do |user|
      puts "#{user.document_id} data: #{user.data}."
    end

    保護您的數據

    如果您使用的是 Web、Android 或 Apple 平台 SDK,請使用Firebase 驗證Cloud Firestore 安全性規則來保護 Cloud Firestore 中的資料。

    以下是一些可用於入門的基本規則集。您可以在控制台的「規則」標籤中修改安全規則。

    需要身份驗證

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

    鎖定模式

    // Deny read/write access to all users under any conditions
    service cloud.firestore {
      match /databases/{database}/documents {
        match /{document=**} {
          allow read, write: if false;
        }
      }
    }
    

    測試模式

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

    在將 Web、Android 或 iOS 應用程式部署到生產環境之前,還應採取措施確保只有您的應用程式用戶端才能存取您的 Cloud Firestore 資料。請參閱應用程式檢查文件。

    如果您使用的是伺服器 SDK 之一,請使用身分識別和存取管理 (IAM)來保護 Cloud Firestore 中的資料。

    觀看影片教學

    有關 Cloud Firestore 行動用戶端庫入門的詳細指南,請觀看以下影片教學之一:

    網路
    iOS+
    安卓

    您可以在 Firebase YouTube 頻道中找到更多影片。

    下一步

    透過以下主題加深您的知識: