递增 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 示例浏览器