このクイックスタートでは、Cloud Firestore を設定し、データを追加してから、追加したデータを Firebase コンソールで表示する方法を示します。
Cloud Firestore データベースを作成する
Firebase プロジェクトをまだ作成していない場合は、作成します。Firebase コンソールで [プロジェクトを追加] をクリックし、画面の指示に従って Firebase プロジェクトを作成するか、Firebase サービスを既存の GCP プロジェクトに追加します。
Firebase コンソールのCloud Firestoreセクションに移動します。既存の Firebase プロジェクトを選択するよう求められます。データベース作成ワークフローに従います。
Cloud Firestore セキュリティ ルールの開始モードを選択します。
- テストモード
モバイルおよび Web クライアント ライブラリの使用を開始するのに適していますが、誰でもデータの読み取りと上書きを行うことができます。テスト後、 「データの保護」セクションを必ず確認してください。
Web、Apple プラットフォーム、または Android SDK を使い始めるには、テスト モードを選択します。
- ロックモード
モバイルおよび Web クライアントからの読み取りと書き込みをすべて拒否します。認証されたアプリケーション サーバー (C#、Go、Java、Node.js、PHP、Python、または Ruby) は引き続きデータベースにアクセスできます。
C#、Go、Java、Node.js、PHP、Python、または Ruby サーバー クライアント ライブラリの使用を開始するには、ロック モードを選択します。
データベースの場所を選択します。
この場所の設定は、プロジェクトのデフォルトの Google Cloud Platform (GCP) リソースの場所です。この場所は、場所の設定を必要とするプロジェクト内の GCP サービス、特にデフォルトのCloud StorageバケットとApp Engineアプリ (Cloud Scheduler を使用する場合に必要) に使用されることに注意してください。
ロケーションを選択できない場合、プロジェクトにはデフォルトの GCP リソース ロケーションがすでに存在します。プロジェクトの作成時、または場所の設定が必要な別のサービスのセットアップ時に設定されました。
[完了]をクリックします。
Cloud Firestore を有効にすると、 Cloud API Managerの API も有効になります。
開発環境をセットアップする
必要な依存関係とクライアント ライブラリをアプリに追加します。
Web version 8
- 指示に従ってFirebase を Web アプリに追加します。
- Firebase ライブラリと Cloud Firestore ライブラリをアプリに追加します:
<script src="https://www.gstatic.com/firebasejs/8.10.1/firebase-app.js"></script> <script src="https://www.gstatic.com/firebasejs/8.10.1/firebase-firestore.js"></script>
Cloud Firestore SDK は npm パッケージとしても利用できます。npm install firebase@8.10.1 --save
Firebase と Cloud Firestore の両方を手動で要求する必要があります。const firebase = require("firebase"); // Required for side-effects require("firebase/firestore");
Web version 9
- 指示に従ってFirebase を Web アプリに追加します。
- Cloud Firestore SDK は npm パッケージとして入手できます。
npm install firebase@9.17.0 --save
Firebase と Cloud Firestore の両方をインポートする必要があります。import { initializeApp } from "firebase/app"; import { getFirestore } from "firebase/firestore";
iOS+
指示に従ってFirebase を Apple アプリに追加します。
Swift Package Manager を使用して、Firebase の依存関係をインストールおよび管理します。
- Xcode で、アプリ プロジェクトを開いた状態で、 File > Swift Packages > Add Package Dependencyに移動します。
- プロンプトが表示されたら、Firebase Apple プラットフォーム SDK リポジトリを追加します。
- Firestore ライブラリを選択します。
- 完了すると、Xcode はバックグラウンドで依存関係の解決とダウンロードを自動的に開始します。
https://github.com/firebase/firebase-ios-sdk
Kotlin+KTX
- 指示に従ってFirebase を Android アプリに追加します。
- Firebase Android BoMを使用して、モジュール (アプリレベル) の Gradle ファイル(通常は
app/build.gradle
) で Cloud Firestore Android ライブラリの依存関係を宣言します。dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:31.2.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-ktx' }
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-ktx:24.4.2' }
Java
- 指示に従ってFirebase を Android アプリに追加します。
- Firebase Android BoMを使用して、モジュール (アプリレベル) の Gradle ファイル(通常は
app/build.gradle
) で Cloud Firestore Android ライブラリの依存関係を宣言します。dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:31.2.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:24.4.2' }
Dart
- まだ行っていない場合は、Flutter アプリでFirebase を構成して初期化します。
- Flutter プロジェクトのルートから、次のコマンドを実行してプラグインをインストールします:
flutter pub add cloud_firestore
- 完了したら、Flutter アプリケーションを再構築します:
flutter run
- オプション:プリコンパイル済みフレームワークを含めることで、iOS と macOS のビルド時間を改善します。
現在、iOS 用の Firestore SDK は、Xcode でのビルドに 5 分以上かかるコードに依存しています。ビルド時間を大幅に短縮するには、Podfile の
target 'Runner' do
ブロックに次の行を追加して、コンパイル済みバージョンを使用できます。target 'Runner' do pod 'FirebaseFirestore', :git => 'https://github.com/invertase/firestore-ios-sdk-frameworks.git', :tag => '8.15.0' # ... end
さらに、CocoaPods を 1.9.1 以降にアップグレードしたことを確認してください:
gem install cocoapods
詳細については、 GitHub の問題を参照してください。
ジャワ
- アプリに 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>
- Gradle の使用:
- 以下の手順に従って、環境内の適切な資格情報で Cloud Firestore を初期化します。
パイソン
- Firebase Admin SDK を Python アプリに追加します:
pip install --upgrade firebase-admin
- 以下の手順に従って、環境内の適切な資格情報で Cloud Firestore を初期化します。
C++
- 指示に従ってFirebase を C++ プロジェクトに追加します。
- 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}")
- デスクトップ統合を設定するには、 Firebase を C++ プロジェクトに追加する を参照してください。
団結
- 指示に従ってFirebase を Unity プロジェクトに追加します。
- Android 用の Unity インターフェース。
- [ファイル] > [ビルド設定] を選択します
- 「プラットフォーム」を「Android」に切り替えて「Switch Platform」をクリック
- [プレイヤー設定…] をクリックします。
- メインの Unity UI で、[Android の設定] の下にある [公開設定] を選択します。
- [縮小] セクションで、リリースとデバッグの両方の設定を [なし] から [ProGuard] に変更します。
Android 向けにビルドする場合は、ProGuarding を有効にして Android DEX 制限を回避します。これを行うには、Unity エディターで次のようにします。
Node.js
- Firebase Admin SDK をアプリに追加します:
npm install firebase-admin --save
- 以下の手順に従って、環境内の適切な資格情報で Cloud Firestore を初期化します。
行け
- Firebase Admin SDK を Go アプリに追加します:
go get firebase.google.com/go
- 以下の手順に従って、環境内の適切な資格情報で Cloud Firestore を初期化します。
PHP
- 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 でアプリケーションを実行する場合、認証する必要はありません。それ以外の場合は、サービス アカウントを設定します。
- 開発環境から認証するには、
- クライアント ライブラリを使用するために必要な、PHP 用のgRPC 拡張機能をインストールして有効にします。
- Cloud Firestore PHP ライブラリをアプリに追加します:
composer require google/cloud-firestore
C#
- 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 でアプリケーションを実行する場合、認証する必要はありません。それ以外の場合は、サービス アカウントを設定します。
- 開発環境から認証するには、
- Cloud Firestore C# ライブラリをアプリの
.csproj
ファイルに追加します:<ItemGroup> <PackageReference Include="Google.Cloud.Firestore" Version="1.1.0-beta01" /> </ItemGroup>
-
Program.cs
ファイルに以下を追加します:using Google.Cloud.Firestore;
ルビー
- 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 でアプリケーションを実行する場合、認証する必要はありません。それ以外の場合は、サービス アカウントを設定します。
- 開発環境から認証するには、
- Cloud Firestore Ruby ライブラリをアプリの
Gemfile
に追加します:gem "google-cloud-firestore"
-
bundle install
を使用して、Gemfile
から依存関係をインストールします。
(省略可)Firebase Local Emulator Suite でプロトタイプを作成してテストする
モバイル デベロッパー向けに、アプリが Cloud Firestore に書き込み、Cloud Firestore から読み取る方法について説明する前に、Cloud Firestore 機能のプロトタイプ作成とテストに使用できる一連のツール、Firebase Local Emulator Suite を紹介しましょう。さまざまなデータ モデルを試したり、セキュリティ ルールを最適化したり、バックエンドと対話するための最も費用対効果の高い方法を見つけようとしている場合、ライブ サービスをデプロイせずにローカルで作業できることは素晴らしいアイデアです。
Cloud Firestore エミュレーターは Local Emulator Suite の一部であり、アプリがエミュレートされたデータベースのコンテンツと構成、および必要に応じてエミュレートされたプロジェクト リソース (関数、他のデータベース、セキュリティ ルール) とやり取りできるようにします。
Cloud Firestore エミュレータを使用するには、いくつかの手順が必要です。
- アプリのテスト構成にコード行を追加して、エミュレーターに接続します。
- ローカル プロジェクト ディレクトリのルートから、
firebase emulators:start
を実行します。 - 通常どおり、Cloud Firestore プラットフォーム SDK を使用して、アプリのプロトタイプ コードから呼び出しを行います。
Cloud Firestore と Cloud Functions に関する詳細なチュートリアルが利用可能です。 Local Emulator Suite Introductionも参照してください。
Cloud Firestore の初期化
Cloud Firestore のインスタンスを初期化します。
Web version 9
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 version 8
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
に置き換えます。
デバイスが接続を失ったときにデータを保持するには、オフライン データの有効化に関するドキュメントを参照してください。
迅速
import FirebaseCore import FirebaseFirestore
FirebaseApp.configure() let db = Firestore.firestore()
Objective-C
@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 を初期化する」を参照してください。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();
パイソン
Cloud Firestore SDK は、環境に応じてさまざまな方法で初期化されます。以下は、最も一般的な方法です。完全なリファレンスについては、「 Admin SDK を初期化する」を参照してください。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 を初期化する」を参照してください。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 } = require('firebase-admin/firestore');
initializeApp(); const db = getFirestore();
- Google Cloud で初期化する
const { initializeApp, applicationDefault, cert } = require('firebase-admin/app'); const { getFirestore, Timestamp, FieldValue } = 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 } = require('firebase-admin/firestore');
const serviceAccount = require('./path/to/serviceAccountKey.json'); initializeApp({ credential: cert(serviceAccount) }); const db = getFirestore();
行け
Cloud Firestore SDK は、環境に応じてさまざまな方法で初期化されます。以下は、最も一般的な方法です。完全なリファレンスについては、「 Admin SDK を初期化する」を参照してください。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 クライアント ライブラリを参照してください。
団結
using Firebase.Firestore; using Firebase.Extensions;
FirebaseFirestore db = FirebaseFirestore.DefaultInstance;
C#
C#
Cloud Firestore クライアントのインストールと作成の詳細については、 Cloud Firestore クライアント ライブラリを参照してください。
ルビー
データを追加
Cloud Firestore はデータをドキュメントに保存し、ドキュメントはコレクションに保存されます。 Cloud Firestore は、ドキュメントに初めてデータを追加するときにコレクションとドキュメントを暗黙的に作成します。コレクションやドキュメントを明示的に作成する必要はありません。
次のサンプル コードを使用して、新しいコレクションとドキュメントを作成します。
Web version 9
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 version 8
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); });
迅速
// Add a new document with a generated ID var ref: DocumentReference? = nil ref = db.collection("users").addDocument(data: [ "first": "Ada", "last": "Lovelace", "born": 1815 ]) { err in if let err = err { print("Error adding document: \(err)") } else { print("Document added with ID: \(ref!.documentID)") } }
Objective-C
// Add a new document with a generated ID __block FIRDocumentReference *ref = [[self.db collectionWithPath:@"users"] addDocumentWithData:@{ @"first": @"Ada", @"last": @"Lovelace", @"born": @1815 } completion:^(NSError * _Nullable error) { if (error != nil) { NSLog(@"Error adding document: %@", error); } else { NSLog(@"Document added with ID: %@", ref.documentID); } }];
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}'));
ジャワ
パイソン
Python
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
行け
PHP
PHP
Cloud Firestore クライアントのインストールと作成の詳細については、 Cloud Firestore クライアント ライブラリを参照してください。
団結
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#
ルビー
ここで、 users
コレクションに別のドキュメントを追加します。このドキュメントには、最初のドキュメントには表示されないキーと値のペア (ミドル ネーム) が含まれていることに注意してください。コレクション内のドキュメントには、さまざまな情報セットを含めることができます。
Web version 9
// 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 version 8
// 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); });
迅速
// Add a second document with a generated ID. ref = db.collection("users").addDocument(data: [ "first": "Alan", "middle": "Mathison", "last": "Turing", "born": 1912 ]) { err in if let err = err { print("Error adding document: \(err)") } else { print("Document added with ID: \(ref!.documentID)") } }
Objective-C
// Add a second document with a generated ID. __block FIRDocumentReference *ref = [[self.db collectionWithPath:@"users"] addDocumentWithData:@{ @"first": @"Alan", @"middle": @"Mathison", @"last": @"Turing", @"born": @1912 } completion:^(NSError * _Nullable error) { if (error != nil) { NSLog(@"Error adding document: %@", error); } else { NSLog(@"Document added with ID: %@", ref.documentID); } }];
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}'));
ジャワ
パイソン
Python
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
行け
PHP
PHP
Cloud Firestore クライアントのインストールと作成の詳細については、 Cloud Firestore クライアント ライブラリを参照してください。
団結
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#
ルビー
データの読み取り
Cloud Firestore にデータを追加したことをすばやく確認するには、 Firebase コンソールのデータ ビューアを使用します。
「get」メソッドを使用してコレクション全体を取得することもできます。
Web version 9
import { collection, getDocs } from "firebase/firestore"; const querySnapshot = await getDocs(collection(db, "users")); querySnapshot.forEach((doc) => { console.log(`${doc.id} => ${doc.data()}`); });
Web version 8
db.collection("users").get().then((querySnapshot) => { querySnapshot.forEach((doc) => { console.log(`${doc.id} => ${doc.data()}`); }); });
迅速
db.collection("users").getDocuments() { (querySnapshot, err) in if let err = err { print("Error getting documents: \(err)") } else { for document in querySnapshot!.documents { print("\(document.documentID) => \(document.data())") } } }
Objective-C
[[self.db collectionWithPath:@"users"] getDocumentsWithCompletion:^(FIRQuerySnapshot * _Nullable snapshot, NSError * _Nullable error) { if (error != nil) { NSLog(@"Error getting documents: %@", error); } else { for (FIRDocumentSnapshot *document in snapshot.documents) { NSLog(@"%@ => %@", document.documentID, document.data); } } }];
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()}"); } });
ジャワ
パイソン
users_ref = db.collection(u'users') docs = users_ref.stream() for doc in docs: print(f'{doc.id} => {doc.to_dict()}')
Python
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
行け
PHP
PHP
Cloud Firestore クライアントのインストールと作成の詳細については、 Cloud Firestore クライアント ライブラリを参照してください。
団結
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#
ルビー
データを保護する
Web、Android、または Apple プラットフォームの SDK を使用している場合は、 Firebase Authenticationと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 データにアクセスできるようにするための手順も実行してください。 App Checkのドキュメントを参照してください。
いずれかのサーバー SDK を使用している場合は、 Identity and Access Management (IAM)を使用して Cloud Firestore のデータを保護します。
ビデオチュートリアルを見る
Cloud Firestore モバイル クライアント ライブラリの使用を開始するための詳細なガイダンスについては、次のビデオ チュートリアルのいずれかをご覧ください。
ウェブ
iOS+
アンドロイド
Firebase のYouTube チャンネルでさらに多くのビデオを見つけることができます。
次のステップ
次のトピックで知識を深めてください。
- Codelabs — Android 、 iOS 、またはWebの Codelab に従って、実際のアプリで Cloud Firestore を使用する方法を学びます。
- データ モデル— 階層データやサブコレクションなど、Cloud Firestore でデータがどのように構造化されているかについて学びます。
- データを追加する- Cloud Firestore でのデータの作成と更新の詳細をご覧ください。
- データを取得する— データを取得する方法の詳細をご覧ください。
- 単純な複合クエリを実行する — 単純な複合クエリを実行する方法を学びます。
- クエリの並べ替えと制限 クエリによって返されるデータを並べ替えて制限する方法を学習します。