Nhóm bộ sưu tập

Mô tả

Trả về tất cả tài liệu từ mọi bộ sưu tập có mã bộ sưu tập được chỉ định, bất kể bộ sưu tập đó có phải là bộ sưu tập con hay không.

Ví dụ

Web

const results = await execute(db.pipeline()
  .collectionGroup("games")
  .sort(field("name").ascending())
  );
Swift
let results = try await db.pipeline()
  .collectionGroup("games")
  .sort([Field("name").ascending()])
  .execute()

Kotlin

val results = db.pipeline()
    .collectionGroup("games")
    .sort(field("name").ascending())
    .execute()

Java

      Task<Pipeline.Snapshot> results = db.pipeline()
    .collectionGroup("games")
    .sort(field("name").ascending())
    .execute();
    
Python
from google.cloud.firestore_v1.pipeline_expressions import Field

results = (
    client.pipeline()
    .collection_group("games")
    .sort(Field.of("name").ascending())
    .execute()
)
Java
Pipeline.Snapshot results =
    firestore
        .pipeline()
        .collectionGroup("games")
        .sort(ascending(field("name")))
        .execute()
        .get();
Bắt đầu
snapshot := client.Pipeline().
	CollectionGroup("games").
	Sort(firestore.Orders(firestore.Ascending(firestore.FieldOf("name")))).
	Execute(ctx)

Hành vi

Để sử dụng giai đoạn collection_group(...), giai đoạn này phải xuất hiện dưới dạng giai đoạn đầu tiên trong quy trình.

Thứ tự của các tài liệu được trả về từ giai đoạn collection_group(...) là không ổn định và không thể dựa vào. Cloud Firestore sẽ cố gắng thực thi truy vấn theo cách hiệu quả nhất có thể, điều này có thể thay đổi thứ tự tuỳ thuộc vào cấu hình giản đồ hoặc chỉ mục. Bạn có thể sử dụng giai đoạn sort(...) tiếp theo để có được một thứ tự xác định.

Ví dụ: đối với các tài liệu sau:

Node.js

await db.collection("cities/SF/departments").doc("building").set({name: "SF Building Deparment", employees: 750});
await db.collection("cities/NY/departments").doc("building").set({name: "NY Building Deparment", employees: 1000});
await db.collection("cities/CHI/departments").doc("building").set({name: "CHI Building Deparment", employees: 900});
await db.collection("cities/NY/departments").doc("finance").set({name: "NY Finance Deparment", employees: 1200});

Bạn có thể sử dụng giai đoạn collection_group(...) để trả về các tài liệu từ mọi bộ sưu tập phòng ban trong tất cả các bộ sưu tập mẹ trong cơ sở dữ liệu.

Node.js

const results = await db.pipeline()
  .collectionGroup("departments")
  .sort(field("employees").ascending())
  .execute();

Truy vấn này tạo ra các tài liệu sau:

  { name: "SF Building Deparment", employees: 750 }
  { name: "CHI Building Deparment", employees: 900 }
  { name: "NY Building Deparment", employees: 1000 }
  { name: "NY Finance Deparment", employees: 1200 }