更新

update(...) ステージは既存のドキュメントを更新します。

たとえば、次のオペレーションは、データモデルの変更をコレクション グループ内のすべてのドキュメントにバックフィルします。パイプラインは、users コレクション グループ内のすべてのドキュメントのうち、そのフィールドがないものに preferences.color フィールドを追加します。

Node.js
const snapshot = await db.pipeline()
   .collectionGroup("users")
   .where(not(exists(field("preferences.color"))))
   .addFields(constant(null).as("preferences.color"))
   .removeFields("color")
   .update()
   .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Constant, Field, Not

snapshot = (
    client.pipeline()
    .collection_group("users")
    .where(Not(Field.of("preferences.color").exists()))
    .add_fields(Constant.of(None).as_("preferences.color"))
    .remove_fields("color")
    .update()
    .execute()
)
Java
Pipeline.Snapshot snapshot = firestore.pipeline()
   .collectionGroup("users")
   .where(not(exists(field("preferences.color"))))
   .addFields(constant((String) null).as("preferences.color"))
   .removeFields("color")
   .update()
   .execute().get();
Go
snapshot := client.Pipeline().
	CollectionGroup("users").
	Where(firestore.Not(firestore.FieldExists(firestore.FieldOf("preferences.color")))).
	AddFields(firestore.Selectables(
		firestore.ConstantOfNull().As("preferences.color"),
	)).
	RemoveFields(firestore.Fields("color")).
	Update().
	Execute(ctx)

動作

すべてのデータ操作言語(DML)ステージは、パイプラインの最後に配置する必要があります。

このステージに移行するドキュメントには、更新するドキュメントを特定するための __name__ フィールドを含める必要があります。ドキュメントが存在しない場合、オペレーションは失敗します。ほとんどの入力ステージ(collection(...)collection_group(...)database(...)documents(...) など)には、デフォルトで __name__ フィールドが含まれています。

必要に応じて、ドキュメントの書き込み直前に適用する transformations を指定できます。これらは、最終出力ステージの直前に add_fields(...) を追加するのと同様に機能し、式は前のドキュメントのコンテキストで実行されます。

レスポンスには、変更されたドキュメント数の概要が含まれます。たとえば、次のレスポンスは、パイプラインが 3 つのドキュメントを変更したことを確認します。

{documents_modified: 3L}

制限事項

  • DML ステージは Cloud Firestore Security Rules をサポートしていません。Cloud Firestore Security Rules を介した DML オペレーションの試行は拒否されます。

  • この機能のプレビュー期間中は、トランザクションで DML ステージを実行できません。整合性の動作の詳細については、整合性をご覧ください。

  • DML ステージの前のステージで同じ __name__ を持つ複数のドキュメントが生成された場合、各インスタンスが処理されます。update(...) の場合、同じターゲット ドキュメントが複数回変更される可能性があります。delete(...) の場合、最初の試行後の後続の試行は no-op になります。