Cloud Firestore Standard エディションを使ってみる

このクイックスタートでは、Cloud Firestore を設定してデータを追加し、追加したデータを Firebase コンソールで表示する方法について説明します。

Cloud Firestore は、モバイル SDK またはウェブ SDK とサーバー クライアント ライブラリをサポートしています。

  • Cloud Firestore は、Android、iOS、ウェブなどの SDK をサポートしています。Cloud Firestore Security RulesFirebase Authentication を組み合わせると、モバイル SDK とウェブ SDK でサーバーレス アプリ アーキテクチャがサポートされ、これによりクライアントは Cloud Firestore データベースに直接接続できます。

  • Cloud Firestore は、C#、Go、Java、Node.js、PHP、Python、Ruby 用のサーバー クライアント ライブラリをサポートしています。データベースへの完全アクセス権を備えた特権的サーバー環境を設定するには、これらのクライアント ライブラリを使用します。これらのライブラリの詳細については、サーバー クライアント ライブラリのクイックスタートをご覧ください。

Cloud Firestore データベースを作成する

  1. まだ Firebase プロジェクトを作成していない場合は作成します。Firebase コンソールで[プロジェクトを追加] をクリックし、画面上の指示に沿って、Firebase プロジェクトを作成するか、Google Cloud プロジェクトに Firebase サービスを追加します。

  2. Firebase コンソールでプロジェクトを開きます。左側のパネルで [ビルド] を展開し、[Firestore データベース] を選択します。

  3. [データベースを作成] をクリックします。

  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 データベースには、Cloud Firestore Security Rules の初期セットが適用されます。プロジェクトに複数のデータベースを作成する場合は、データベースごとに Cloud Firestore Security Rules をデプロイできます。

  6. [作成] をクリックします。

Cloud Firestore を有効にすると、Cloud API Manager で API も有効になります。

開発環境を設定する

必要な依存関係とクライアント ライブラリをアプリに追加します。

Web

  1. Firebase をウェブアプリに追加するの手順に沿って操作します。
  2. Cloud Firestore SDK は、npm パッケージとしても提供されています。
    npm install firebase@12.8.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/12.8.0/firebase-app-compat.js"></script>
    <script src="https://www.gstatic.com/firebasejs/12.8.0/firebase-firestore-compat.js"></script>
    Cloud Firestore SDK は、npm パッケージとしても提供されています。
    npm install firebase@12.8.0 --save
    Firebase と Cloud Firestore の両方を手動で require する必要があります。
    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(Swift パッケージ)] > [Add Package Dependency(パッケージの依存関係を追加)] の順に移動します。
  2. プロンプトが表示されたら、Firebase Apple プラットフォーム SDK リポジトリを追加します。
  3.   https://github.com/firebase/firebase-ios-sdk
      
  4. Firestore ライブラリを選択します。
  5. 上記の作業が完了すると、Xcode は依存関係の解決とバックグラウンドでのダウンロードを自動的に開始します。
Android
  1. Android アプリに Firebase を追加するの手順に沿って操作します。
  2. Firebase Android 部品構成表を使用して、モジュール(アプリレベル)の Gradle ファイル(通常は app/build.gradle.kts または app/build.gradle)で Android 向け Cloud Firestore ライブラリの依存関係を宣言します。
    dependencies {
        // Import the BoM for the Firebase platform
        implementation(platform("com.google.firebase:firebase-bom:34.8.0"))
    
        // Declare the dependency for the Cloud Firestore library
        // When using the BoM, you don't specify versions in Firebase library dependencies
        implementation("com.google.firebase:firebase-firestore")
    }

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

    Kotlin 固有のライブラリ モジュールをお探しの場合、2023 年 10 月のリリース以降は、Kotlin と Java のどちらのデベロッパーもメイン ライブラリ モジュールを利用できるようになります(詳しくは、このイニシアチブに関するよくある質問をご覧ください)。

Dart

  1. まだ行っていない場合は、Flutter アプリで Firebase の構成と初期化を行います。
  2. Flask プロジェクトのルートから、次のコマンドを実行してプラグインをインストールします。
    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 での問題をご覧ください。

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 Build Debug ガイドをご覧ください。
    • 圧縮を有効 にした後も、参照されるメソッドの数が制限を超える場合は、次の場所で multidex を有効にすることもできます。
      • [Player Settings] の下の [Custom Gradle Template] が有効な場合は、mainTemplate.gradle
      • Android Studio を使用してエクスポートされたプロジェクトをビルドする場合は、モジュール レベルの build.gradle ファイル。

(省略可)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 FirestoreCloud 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 コレクションに追加します。このドキュメントには、最初のドキュメントに表示されない Key-Value ペア(ミドルネーム)が含まれています。コレクション内のドキュメントには、それぞれ異なる情報のセットを含めることができます。

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 AuthenticationCloud Firestore Security Rules を使用して、Cloud 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 チャンネルにはさらに多くの動画があります。

次のステップ

次のトピックで知識を深めてください。