更新

update(...) 阶段会更新现有文档。

示例

例如,以下操作会将数据模型更改回填到合集组中的所有文档。流水线会将 preferences.color 字段添加到 users 合集组中缺少该字段的所有文档。

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();

行为

所有数据操纵语言 (DML) 阶段都必须位于流水线的末尾。

进入此阶段的文档必须包含 __name__ 字段,以标识要更新的文档。如果任何文档不存在,操作都会失败。 大多数输入阶段(例如 collection(...), collection_group(...), database(...)documents(...))默认包含 __name__ 字段。

您可以选择性地提供 transformations,以便在写入文档之前应用。这些转换的作用与在最终输出阶段之前添加 add_fields(...)完全相同,并且 表达式会在之前的文档的上下文中运行。

响应包含修改的文档数量的摘要。 例如,以下响应确认流水线修改了三个文档:

{documents_modified: 3L}

限制

  • DML 阶段不支持 Cloud Firestore Security Rules。通过 Cloud Firestore Security Rules 尝试执行 DML 操作会被拒绝。

  • 在此功能的预览版期间,您无法在事务中运行 DML 阶段。如需详细了解一致性行为,请参阅 一致性

  • 如果 DML 阶段之前的阶段生成了多个具有相同 __name__ 的文档,则系统会处理每个实例。对于 update(...),这意味着同一个目标文档可能会被多次修改。对于 delete(...),第一次尝试之后的所有后续尝试都将是空操作。