Thêm trường

Mô tả

Thêm các trường mới vào tài liệu do giai đoạn trước tạo ra.

Tài liệu được tạo sẽ chứa tất cả các trường trong giai đoạn trước cùng với tất cả các trường mới được thêm vào, ghi đè mọi trường có cùng tên trong tài liệu trước đó. Giai đoạn add_fields(...) cho phép cập nhật các trường lồng nhau bằng cách chỉ định tên trường lồng nhau làm bí danh.

Ví dụ

Web

const result = await execute(db.pipeline()
  .collection("books")
  .select(field("soldBooks").add(field("unsoldBooks")).as("totalBooks"))
);
Swift
let result = try await db.pipeline()
  .collection("books")
  .select([Field("soldBooks").add(Field("unsoldBooks")).as("totalBooks")])
  .execute()

Kotlin

val result = db.pipeline()
    .collection("books")
    .select(Expression.add(field("soldBooks"), field("unsoldBooks")).alias("totalBooks"))
    .execute()

Java

      Task<Pipeline.Snapshot> result = db.pipeline()
    .collection("books")
    .select(Expression.add(field("soldBooks"), field("unsoldBooks")).alias("totalBooks"))
    .execute();
    
Python
from google.cloud.firestore_v1.pipeline_expressions import Field

result = (
    client.pipeline()
    .collection("books")
    .select(Field.of("soldBooks").add(Field.of("unsoldBooks")).as_("totalBooks"))
    .execute()
)
Java
Pipeline.Snapshot result =
    firestore
        .pipeline()
        .collection("books")
        .select(add(field("soldBooks"), field("unsoldBooks")).as("totalBooks"))
        .execute()
        .get();

Hành vi

Các trường trùng lặp

Việc chỉ định một biểu thức có bí danh đã có trong tài liệu ở giai đoạn trước sẽ khiến giai đoạn add_fields(...) ghi đè trường trước đó. Bạn có thể dùng cách này để liên kết nhiều biểu thức trên cùng một tên trường, chẳng hạn như:

Node.js

const results = await db.pipeline()
  .collection("/users")
  .addFields(field('age').abs().as('age'))
  .addFields(field('age').add(10).as('age'))
  .execute();

Các trường lồng nhau

Bạn có thể cập nhật các trường lồng nhau (ví dụ: các trường có cú pháp .) trong giai đoạn này. Điều này giúp bạn có thể cập nhật một trường "tại chỗ", chẳng hạn như trong:

Node.js

const results = await db.pipeline()
  .collection("/users")
  .addFields(field('address.city').toLower().as('address.city'))
  .execute();

Việc chỉ định một biểu thức cho một trường lồng nhau cũng sẽ ngầm tạo mọi trường mẹ bị thiếu.