集合组(输入阶段)

说明

返回具有指定集合 ID 的任何集合中的所有文档,无论其父级是什么。

示例

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
Android
val results = db.pipeline()
    .collectionGroup("games")
    .sort(field("name").ascending())
    .execute()
Java
Android
      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();
Go
snapshot := client.Pipeline().
	CollectionGroup("games").
	Sort(firestore.Orders(firestore.Ascending(firestore.FieldOf("name")))).
	Execute(ctx)

行为

如需使用 collection_group(...) 阶段,它必须作为流水线中的第一个阶段出现。

collection_group(...) 阶段返回的文档顺序不稳定,不应依赖。Firestore 会尝试以尽可能高效的方式执行查询,这可能会根据架构或索引配置更改顺序。可使用后续的 sort(...) 阶段来获得确定性的顺序。

例如,对于以下文档:

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

collection_group(...) 阶段可用于返回数据库中所有父集合下的各个部门集合内的所有文档。

Node.js

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

此查询会生成以下文档:

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