Firestore ドキュメント フィールドを増やす

Increment を使用して Firestore ドキュメント フィールドを更新する フィールドが存在しない場合、Firestore はフィールドを作成し、インクリメントします。

もっと見る

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

コードサンプル

C#

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

DocumentReference washingtonRef = db.Collection("cities").Document("DC");

// Atomically increment the population of the city by 50.
await washingtonRef.UpdateAsync("Regions", FieldValue.Increment(50));

Go

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

import (
	"context"
	"fmt"

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

// updateDocumentIncrement increments the population of the city document in the
// cities collection by 50.
func updateDocumentIncrement(projectID, city string) error {
	// projectID := "my-project"

	ctx := context.Background()

	client, err := firestore.NewClient(ctx, projectID)
	if err != nil {
		return fmt.Errorf("firestore.NewClient: %w", err)
	}
	defer client.Close()

	dc := client.Collection("cities").Doc(city)
	_, err = dc.Update(ctx, []firestore.Update{
		{Path: "population", Value: firestore.Increment(50)},
	})
	if err != nil {
		return fmt.Errorf("Update: %w", err)
	}

	return nil
}

Java

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

DocumentReference washingtonRef = db.collection("cities").document("DC");

// Atomically increment the population of the city by 50.
final ApiFuture<WriteResult> updateFuture =
    washingtonRef.update("population", FieldValue.increment(50));

Node.js

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

// ...
const washingtonRef = db.collection('cities').doc('DC');

// Atomically increment the population of the city by 50.
const res = await washingtonRef.update({
  population: FieldValue.increment(50)
});

PHP

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

$cityRef = $db->collection('samples/php/cities')->document('DC');

// Atomically increment the population of the city by 50.
$cityRef->update([
    ['path' => 'regions', 'value' => FieldValue::increment(50)]
]);

Python

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

washington_ref = db.collection("cities").document("DC")

washington_ref.update({"population": firestore.Increment(50)})

Ruby

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

city_ref = firestore.doc "#{collection_path}/DC"
city_ref.update({ population: firestore.field_increment(50) })

次のステップ

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