集合(输入阶段)

说明

返回指定集合中的所有文档。集合可以嵌套。

示例

Web

const results = await execute(db.pipeline()
  .collection("users/bob/games")
  .sort(field("name").ascending())
  );
Swift
let results = try await db.pipeline()
  .collection("users/bob/games")
  .sort([Field("name").ascending()])
  .execute()
Kotlin
Android
val results = db.pipeline()
    .collection("users/bob/games")
    .sort(field("name").ascending())
    .execute()
Java
Android
Task<Pipeline.Snapshot> results = db.pipeline()
    .collection("users/bob/games")
    .sort(field("name").ascending())
    .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field

results = (
    client.pipeline()
    .collection("users/bob/games")
    .sort(Field.of("name").ascending())
    .execute()
)
Java
Pipeline.Snapshot results =
    firestore
        .pipeline()
        .collection("users/bob/games")
        .sort(ascending(field("name")))
        .execute()
        .get();
Go
snapshot := client.Pipeline().
	Collection("users/bob/games").
	Sort(firestore.Orders(firestore.Ascending(firestore.FieldOf("name")))).
	Execute(ctx)

行为

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

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

例如,对于以下文档:

Node.js

await db.collection("cities").doc("SF").set({name: "San Francsico", state: "California"});
await db.collection("cities").doc("NYC").set({name: "New York City", state: "New York"});
await db.collection("cities").doc("CHI").set({name: "Chicago", state: "Illinois"});
await db.collection("states").doc("CA").set({name: "California"});

collection 阶段可用于检索 cities 集合中的所有城市,然后按名称升序对它们进行排序。

Node.js

const results = await db.pipeline()
  .collection("/cities")
  .sort(field("name").ascending())
  .execute();

此查询会生成以下文档:

  { name: "Chicago", state: "Illinois" }
  { name: "New York City", state: "New York" }
  { name: "San Francisco", state: "California" }

子集合

您还可以通过提供阶段的完整路径,使用 collection(...) 阶段来定位特定父级下的集合。

例如,对于以下文档:

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

在此示例中,我们只希望获取纽约市的部门。

Node.js

const results = await db.pipeline()
  .collection("/cities/NY/departments")
  .sort(field("employees").ascending())
  .execute();

这将返回完整路径 cities/NY/departments 下的所有部门。

  { name: "NY Building Deparment", employees: 1000 }
  { name: "NY Finance Deparment", employees: 1200 }