說明
傳回指定集合中的所有文件。集合可以巢狀結構。
範例
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
val results = db.pipeline() .collection("users/bob/games") .sort(field("name").ascending()) .execute()
Java
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 }