カスタムタイプを使用して Firestore ドキュメントを取得する

カスタムタイプを使用して Firestore ドキュメントを取得します。

もっと見る

このコードサンプルを含む詳細なドキュメントについては、以下をご覧ください。

コードサンプル

C#

Firestore に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

DocumentReference docRef = db.Collection("cities").Document("BJ");
DocumentSnapshot snapshot = await docRef.GetSnapshotAsync();
if (snapshot.Exists)
{
    Console.WriteLine("Document data for {0} document:", snapshot.Id);
    City city = snapshot.ConvertTo<City>();
    Console.WriteLine("Name: {0}", city.Name);
    Console.WriteLine("State: {0}", city.State);
    Console.WriteLine("Country: {0}", city.Country);
    Console.WriteLine("Capital: {0}", city.Capital);
    Console.WriteLine("Population: {0}", city.Population);
}
else
{
    Console.WriteLine("Document {0} does not exist!", snapshot.Id);
}

Go

Firestore に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。


import (
	"context"
	"fmt"

	"cloud.google.com/go/firestore"
)

func docAsEntity(ctx context.Context, client *firestore.Client) (*City, error) {
	dsnap, err := client.Collection("cities").Doc("BJ").Get(ctx)
	if err != nil {
		return nil, err
	}
	var c City
	dsnap.DataTo(&c)
	fmt.Printf("Document data: %#v\n", c)
	return &c, nil
}

Java

Firestore に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

DocumentReference docRef = db.collection("cities").document("BJ");
// asynchronously retrieve the document
ApiFuture<DocumentSnapshot> future = docRef.get();
// block on response
DocumentSnapshot document = future.get();
City city = null;
if (document.exists()) {
  // convert document to POJO
  city = document.toObject(City.class);
  System.out.println(city);
} else {
  System.out.println("No such document!");
}

PHP

Firestore に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

$docRef = $db->collection('samples/php/cities')->document('SF');
$snapshot = $docRef->snapshot();
$city = City::fromArray($snapshot->data());

if ($snapshot->exists()) {
    printf('Document data:' . PHP_EOL);
    print((string) $city);
} else {
    printf('Document %s does not exist!' . PHP_EOL, $snapshot->id());
}

Python

Firestore に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

doc_ref = db.collection("cities").document("BJ")

doc = doc_ref.get()
city = City.from_dict(doc.to_dict())
print(city)

次のステップ

他の Google Cloud プロダクトに関連するコードサンプルの検索およびフィルタ検索を行うには、Google Cloud のサンプルをご覧ください。