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 管理器中启用了相应 API。

设置开发环境

将所需的依赖项和客户端库添加到您的应用。

Web 命名空间型 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 模块化 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(Swift 软件包)> Add Package Dependency(添加软件包依赖项)
  2. 出现提示时,添加 Firebase Apple 平台 SDK 代码库:
  3.   https://github.com/firebase/firebase-ios-sdk
      
  4. 选择 Firestore 库。
  5. 完成之后,Xcode 将会自动开始在后台解析和下载您的依赖项。
Android
  1. 按照相关说明将 Firebase 添加到您的 Android 应用
  2. 使用 Firebase Android BoM模块(应用级)Gradle 文件(通常是 app/build.gradle.ktsapp/build.gradle)中声明 Cloud Firestore Android 库的依赖项。
    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 所依赖的代码可能需要长达 5 分钟时间才能在 Xcode 中构建完毕。如需显著缩短构建时间,您可以使用预编译版本,只需将下面的代码添加到 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 上的问题

Java
  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 依赖项。将以下内容添加到您的模块(应用级)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++ 项目
Unity
  1. 按照相关说明将 Firebase 添加到您的 Unity 项目
  2. 使用 Unity 界面配置您的项目以缩减 Android build 的大小。
  3. 您必须缩减 build 的大小以避免出现消息 Error while merging dex archives

    • 可在 Player Settings > Android > Publishing Settings > Minify 中找到该选项。
    • 这些选项可能会因 Unity 的不同版本而异,因此请参阅官方 Unity 文档Firebase Unity Build 调试指南
    • 如果在启用缩减大小后,引用的方法数量仍然超过上限,另一种方法是在以下位置启用 multidex
      • mainTemplate.gradle(如果启用了 Player Settings 下的 Custom Gradle Template
      • 模块级 build.gradle 文件(如果您使用 Android Studio 构建导出的项目)。
Node.js
  1. 将 Firebase Admin SDK 添加到您的应用中:
    npm install firebase-admin --save
  2. 按照以下说明在您的环境中使用适当的凭据初始化 Cloud Firestore。
Go
  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. 在您的 .csproj 文件中,将 Cloud Firestore C# 库添加到您的应用中:
    <ItemGroup>
      <PackageReference Include="Google.Cloud.Firestore" Version="1.1.0-beta01" />
    </ItemGroup>
  3. 将以下内容添加到 Program.cs 文件:
    using Google.Cloud.Firestore;
Ruby
  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. 在您的 Gemfile 中,将 Cloud Firestore Ruby 库添加到您的应用中:
    gem "google-cloud-firestore"
  3. 使用以下命令从 Gemfile 安装依赖项:
    bundle install

(可选)使用 Firebase Local Emulator Suite 进行原型设计和测试

对于移动开发者,在介绍应用如何对 Cloud Firestore 执行读写操作之前,我们先介绍一套可用于对 Cloud Firestore 功能进行原型设计和测试的工具:Firebase Local Emulator Suite。如果您在尝试使用不同的数据模型、优化安全规则,或设法寻找最经济有效的方式与后端进行交互,那么无需实际部署即可在本地进行上述工作是非常理想的。

Cloud Firestore 模拟器是 Local Emulator Suite 的一部分,通过该套件,您的应用可以与模拟的数据库内容和配置进行交互,以及视需要与您的模拟项目资源(函数、其他数据库和安全规则)进行交互。

如需使用 Cloud Firestore 模拟器,只需完成几个步骤:

  1. 向应用的测试配置添加一行代码以连接到模拟器。
  2. 从本地项目的根目录运行 firebase emulators:start
  3. 照常使用 Cloud Firestore 平台 SDK 从应用的原型设计代码进行调用。

我们提供详细的 Cloud Firestore 和 Cloud Functions 演示。您还应该参阅 Local Emulator Suite 简介

初始化 Cloud Firestore

初始化 Cloud Firestore 的实例:

Web 模块化 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 替换为 Web 应用的 firebaseConfig

如需在设备的网络连接中断时保留数据,请参阅启用离线数据文档。

Web 命名空间型 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 替换为 Web 应用的 firebaseConfig

如需在设备的网络连接中断时保留数据,请参阅启用离线数据文档。

Swift
注意:此产品不适用于 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;
Java
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();
      
    Go
    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);
        }
    }
    Unity
    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);
    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."

    添加数据

    Cloud Firestore 将数据存储在文档中,而文档存储在集合中。在您首次向文档添加数据时,Cloud Firestore 就会隐式创建集合和文档。您不需要显式创建集合或文档。

    使用以下示例代码创建一个新集合和一个新文档。

    Web 模块化 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 命名空间型 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);
    });
    Swift
    注意:此产品不适用于 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}'));
    Java
    DocumentReference docRef = db.collection("users").document("alovelace");
    // Add document data  with id "alovelace" using a hashmap
    Map<String, Object> data = new HashMap<>();
    data.put("first", "Ada");
    data.put("last", "Lovelace");
    data.put("born", 1815);
    //asynchronously write data
    ApiFuture<WriteResult> result = docRef.set(data);
    // ...
    // result.get() blocks on response
    System.out.println("Update time : " + result.get().getUpdateTime());
    Python
    doc_ref = db.collection("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
    });
    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)
    }
    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);
    Unity
    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);
    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."

    现在,将另一个文档添加到 users 集合中。请注意,此文档包含第一个文档中没有的一个键值对(中间名)。集合中的文档可以包含不同的信息集。

    Web 模块化 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 命名空间型 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);
    });
    Swift
    注意:此产品不适用于 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}'));
    Java
    DocumentReference docRef = db.collection("users").document("aturing");
    // Add document data with an additional field ("middle")
    Map<String, Object> data = new HashMap<>();
    data.put("first", "Alan");
    data.put("middle", "Mathison");
    data.put("last", "Turing");
    data.put("born", 1912);
    
    ApiFuture<WriteResult> result = docRef.set(data);
    System.out.println("Update time : " + result.get().getUpdateTime());
    Python
    doc_ref = db.collection("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
    });
    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)
    }
    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);
    Unity
    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);
    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."

    读取数据

    使用 Firebase 控制台中的数据查看器可以快速验证您是否已将数据添加到 Cloud Firestore。

    您也可以使用“get”方法来检索整个集合。

    Web 模块化 API

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

    Web 命名空间型 API

    db.collection("users").get().then((querySnapshot) => {
        querySnapshot.forEach((doc) => {
            console.log(`${doc.id} => ${doc.data()}`);
        });
    });
    Swift
    注意:此产品不适用于 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()}");
      }
    });
    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"));
    }
    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());
    });
    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())
    }
    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);
    Unity
    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();
    }
    Ruby
    users_ref = firestore.col collection_path
    users_ref.get do |user|
      puts "#{user.document_id} data: #{user.data}."
    end

    保护您的数据

    如果您使用的是 Web、Android 或 Apple 平台 SDK,请使用 Firebase AuthenticationCloud 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 数据。请参阅 App Check 文档。

    如果您使用的是服务器 SDK 之一,请通过 Identity and Access Management (IAM) 来保护 Cloud Firestore 中的数据。

    观看视频教程

    如需查看详细的 Cloud Firestore 移动客户端库入门指南,请观看以下视频教程之一:

    Web
    iOS+
    Android

    您可以在 Firebase YouTube 频道中找到更多视频。

    后续步骤

    通过以下各主题深入了解相关知识: