使用合并更新 Firestore 文档

使用合并更新 Firestore 文档

深入探索

如需查看包含此代码示例的详细文档,请参阅以下内容:

代码示例

C#

如需向 Firestore 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

DocumentReference docRef = db.Collection("cities").Document("LA");
Dictionary<string, object> update = new Dictionary<string, object>
{
    { "capital", false }
};
await docRef.SetAsync(update, SetOptions.MergeAll);

Go

如需向 Firestore 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证


import (
	"context"
	"log"

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

func updateDocCreateIfMissing(ctx context.Context, client *firestore.Client) error {
	_, err := client.Collection("cities").Doc("BJ").Set(ctx, map[string]interface{}{
		"capital": true,
	}, firestore.MergeAll)

	if err != nil {
		// Handle any errors in an appropriate way, such as returning them.
		log.Printf("An error has occurred: %s", err)
	}

	return err
}

Java

如需向 Firestore 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

// asynchronously update doc, create the document if missing
Map<String, Object> update = new HashMap<>();
update.put("capital", true);

ApiFuture<WriteResult> writeResult =
    db.collection("cities").document("BJ").set(update, SetOptions.merge());
// ...
System.out.println("Update time : " + writeResult.get().getUpdateTime());

Node.js

如需向 Firestore 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

const cityRef = db.collection('cities').doc('BJ');

const res = await cityRef.set({
  capital: true
}, { merge: true });

PHP

如需向 Firestore 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

$cityRef = $db->collection('samples/php/cities')->document('BJ');
$cityRef->set([
    'capital' => true
], ['merge' => true]);

Python

如需向 Firestore 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

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

city_ref.set({"capital": True}, merge=True)

Ruby

如需向 Firestore 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

city_ref = firestore.doc "#{collection_path}/LA"
city_ref.set({ capital: false }, merge: true)

后续步骤

如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器