開始使用 Firestore Standard 版

本快速入門導覽課程說明如何設定 Cloud Firestore、新增廣告資料,然後在 Firebase 控制台查看剛新增的廣告資料。

Cloud Firestore 支援行動或網頁 SDK 和伺服器用戶端程式庫:

  • Cloud Firestore 支援 Android、iOS 和網頁等 SDK。搭配 Cloud Firestore Security Rules 和 Firebase Authentication,行動和網頁 SDK 支援無伺服器應用程式架構,用戶端可直接連線至 Cloud Firestore 資料庫。

  • Cloud Firestore 支援 C#、Go、Java、Node.js、PHP、Python 和 Ruby 的伺服器用戶端程式庫。您可以使用這些用戶端程式庫,設定具備資料庫完整存取權的特殊權限伺服器環境。如要進一步瞭解這些程式庫,請參閱伺服器用戶端程式庫快速入門導覽課程。

如需 AI 輔助,請將下方提示詞複製到 AI 程式設計代理 (例如 Android Studio 內建 Gemini、Antigravity、Claude Code、Codex 和 Cursor)。您可以自訂提示,並與代理反覆調整。如需詳細安裝資訊,請參閱 Firebase 代理技能。

Help me use Firebase in my app.
1. Make sure that **Firebase agent skills** are installed and updated. For Claude Code, Codex, or Cursor agents, help me install the Firebase plugin. For other agents, run `npx skills add firebase/agent-skills`. Always try to use **Firebase agent skills** for Firebase-related tasks.
2. Help me set up and use Firebase for the backend of my app. Set up Firestore database in **Standard edition**. Help me to choose the best location for my database instance.

建立 Cloud Firestore 資料庫

  1. 如果您尚未建立 Firebase 專案,請前往 Firebase 控制台,按一下「Add project」(新增專案),然後按照畫面上的指示建立 Firebase 專案,或將 Firebase 服務新增至現有的 Google Cloud 專案。

  2. 在左側面板中,依序前往「Databases & Storage」(資料庫和儲存空間) >「Firestore」。

  3. 按一下 [Create database] (建立資料庫)。

  4. 選取資料庫的位置。

    如果無法選取位置,代表專案的「預設 Google Cloud 資源位置」已設定。專案的某些資源 (例如預設 Cloud Firestore 執行個體) 具有共同的位置依附元件,您可以在建立專案時設定其位置,也可以在設定其他具有此位置依附元件的服務時設定其位置。

  5. 選取 Cloud Firestore Security Rules 的起始模式:

    測試模式

    適合用於開始使用行動和網頁用戶端程式庫,但允許任何人讀取及覆寫您的資料。測試完成後,請務必詳閱「保護資料」一節。

    如要開始使用網頁、Apple 平台或 Android SDK,請選取測試模式。

    正式環境模式

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

    如要開始使用 C#、Go、Java、Node.js、PHP、Python 或 Ruby 伺服器用戶端程式庫,請選取正式環境模式。

    初始 Cloud Firestore Security Rules 組合會套用至預設 Cloud Firestore 資料庫。如果您為專案建立多個資料庫,可以為每個資料庫部署 Cloud Firestore Security Rules。

  6. 點選「建立」。

啟用 Cloud Firestore 時,系統也會在 Cloud API Manager 中啟用 API。

設定開發環境

將必要的依附元件和用戶端程式庫新增至應用程式。

Web

  1. 按照操作說明將 Firebase 新增至網頁應用程式。
  2. Cloud Firestore SDK 以 npm 套件的形式提供。
    npm install firebase@13.0.0 --save
    您需要同時匯入 Firebase 和 Cloud Firestore。
    import { initializeApp } from "firebase/app";
    import { getFirestore } from "firebase/firestore";

Web

  1. 按照操作說明將 Firebase 新增至網頁應用程式。
  2. 將 Firebase 和 Cloud Firestore 程式庫新增至應用程式:
    <script src="https://www.gstatic.com/firebasejs/13.0.0/firebase-app-compat.js"></script>
    <script src="https://www.gstatic.com/firebasejs/13.0.0/firebase-firestore-compat.js"></script>
    Cloud Firestore SDK 也提供 npm 套件。
    npm install firebase@13.0.0 --save
    您必須手動要求 Firebase 和 Cloud Firestore。
    import firebase from "firebase/compat/app";
    // Required for side-effects
    import "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 會自動開始在背景解析及下載依附元件。
Android
  1. 按照操作說明將 Firebase 新增至 Android 應用程式。
  2. 使用 Firebase Android BoM,在模組 (應用程式層級) Gradle 檔案 (通常是 app/build.gradle.kts 或 app/build.gradle) 中,宣告 Cloud Firestore Android 程式庫的依附元件。
    dependencies {
        // Import the BoM for the Firebase platform
        implementation(platform("com.google.firebase:firebase-bom:35.0.1"))
    
        // 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 程式庫版本。

    (替代方案) 宣告 Firebase 程式庫依附元件,不使用 BoM

    如果選擇不使用 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:27.0.0")
    }

    想尋找 Kotlin 專屬程式庫模組嗎?自 2023 年 10 月版本起,Kotlin 和 Java 開發人員都可以依附主要程式庫模組 (詳情請參閱這項計畫的常見問題)。

Dart

  1. 如果您尚未設定及初始化 Firebase,請先在 Flutter 應用程式中完成這些步驟。
  2. 在 Flutter 專案的根目錄中,執行下列指令來安裝外掛程式:
    flutter pub add cloud_firestore
  3. 完成後,請重新建構 Flutter 應用程式:
    flutter run
  4. 選用:加入預先編譯的架構,縮短 iOS 和 macOS 建構時間。

    目前,Firestore SDK for iOS 依賴的程式碼在 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_core 的 firebase_sdk_version.rb 檔案中指定的 Firebase iOS SDK 版本。如果您使用的不是最新版本 firebase_core,請在本機 Pub 套件快取 (通常是 ~/.pub-cache) 中尋找這個檔案。

    此外,請務必將 CocoaPods 升級至 1.9.1 以上版本:

    gem install cocoapods

    詳情請參閱 GitHub 上的問題。

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 版本。
  3. 您必須壓縮建構作業,以免系統顯示 Error while merging dex archives 訊息。

    • 這個選項位於「Player Settings」>「Android」>「Publishing Settings」>「Minify」。
    • 不同版本的 Unity 可能會有不同的選項,請參閱官方 Unity 說明文件和 Firebase Unity 建構偵錯指南。
    • 如果啟用壓縮後,參照的方法數量仍超過限制,另一個選項是在以下位置啟用 multidex:
      • 如果已啟用「Player Settings」下方的「Custom Gradle Template」,則為 mainTemplate.gradle
      • 或模組層級 build.gradle 檔案 (如果您使用 Android Studio 建構匯出的專案)。

(選用) 使用 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

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

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。

如要在裝置連線中斷時保留資料,請參閱「啟用離線資料」說明文件。

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

// 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;
C++
// Make sure the call to `Create()` happens some time before you call Firestore::GetInstance().
App::Create();
Firestore* db = Firestore::GetInstance();
Unity
using Firebase.Firestore;
using Firebase.Extensions;
FirebaseFirestore db = FirebaseFirestore.DefaultInstance;

新增資料

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

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

Web

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

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

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

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

Web

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

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

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

讀取資料

使用 Firebase 控制台中的資料檢視器,快速確認您已將資料新增至 Cloud Firestore。

您也可以使用「get」方法擷取整個集合。

Web

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

const querySnapshot = await getDocs(collection(db, "users"));
querySnapshot.forEach((doc) => {
  console.log(doc.id, "=>", doc.data());
});

Web

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

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

確保資料安全

如果您使用的是網頁、Android 或 Apple 平台 SDK,請使用 Firebase Authentication 和 Cloud Firestore Security Rules 保護 Cloud Firestore 中的資料。

以下是一些基本規則集,可協助您快速上手。如要修改安全性規則,請前往 Firebase 控制台,依序點選「資料庫和儲存空間」>「Firestore」>「規則」分頁標籤。

需要驗證

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

正式環境模式

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

將網頁、Android 或 iOS 應用程式部署至正式環境前,請務必採取相關步驟,確保只有您的應用程式用戶端可以存取 Cloud Firestore 資料。請參閱 App Check 說明文件。

如果您使用其中一個伺服器 SDK,請透過 Identity and Access Management (IAM) 保護 Cloud Firestore 中的資料。

觀看教學影片

如需 Cloud Firestore 行動用戶端程式庫的詳細入門指南,請觀看下列任一教學影片:

網頁
iOS+
Android

如要觀看更多影片,請前往 Firebase YouTube 頻道。

後續步驟

請參閱下列主題,深入瞭解相關知識:

  • 程式碼實驗室:按照 Android、iOS 或網頁的程式碼實驗室,瞭解如何在實際應用程式中使用 Cloud Firestore。
  • 資料模型:進一步瞭解 Cloud Firestore 中的資料結構,包括階層式資料和子集合。
  • 新增資料:進一步瞭解如何在 Cloud Firestore 中建立及更新資料。
  • 取得資料:進一步瞭解如何擷取資料。
  • 執行簡單和複合查詢:瞭解如何執行簡單和複合查詢。
  • 排序及限制查詢:瞭解如何排序及限制查詢傳回的資料。
  • Firebase 代理技能:瞭解如何強化 AI 開發工具,更有效地執行工作,並採用 Cloud Firestore 最佳做法 (例如編寫 Cloud Firestore Security Rules)。