了解 2023 年 Google I/O 大会上介绍的 Firebase 亮点。了解详情

使用 Cloud Firestore 訂購和限制數據

Cloud Firestore 提供了強大的查詢功能,用於指定您要從集合中檢索哪些文檔。這些查詢也可以與get()addSnapshotListener()一起使用,如獲取數據中所述。

訂單和限制數據

默認情況下,查詢會按文檔 ID 升序檢索滿足查詢的所有文檔。您可以使用orderBy()指定數據的排序順序,並且可以使用limit()限制檢索的文檔數量。如果您指定limit() ,則該值必須大於或等於零。

例如,您可以按字母順序查詢前 3 個城市:

Web modular API

import { query, orderBy, limit } from "firebase/firestore";  

const q = query(citiesRef, orderBy("name"), limit(3));

Web namespaced API

citiesRef.orderBy("name").limit(3);
迅速
注意:此產品不適用於 watchOS 和 App Clip 目標。
citiesRef.order(by: "name").limit(to: 3)
目標-C
注意:此產品不適用於 watchOS 和 App Clip 目標。
[[citiesRef queryOrderedByField:@"name"] queryLimitedTo:3];

Kotlin+KTX

citiesRef.orderBy("name").limit(3)

Java

citiesRef.orderBy("name").limit(3);

Dart

final citiesRef = db.collection("cities");
citiesRef.orderBy("name").limit(3);
爪哇
Query query = cities.orderBy("name").limit(3);
Query query = cities.orderBy("name").limitToLast(3);
Python
cities_ref = db.collection("cities")
query = cities_ref.order_by("name").limit_to_last(2)
results = query.get()

Python

cities_ref = db.collection("cities")
query = cities_ref.order_by("name").limit_to_last(2)
results = await query.get()
C++
cities_ref.OrderBy("name").Limit(3);
節點.js
const firstThreeRes = await citiesRef.orderBy('name').limit(3).get();
query := cities.OrderBy("name", firestore.Asc).Limit(3)
query := cities.OrderBy("name", firestore.Asc).LimitToLast(3)
PHP

PHP

有關安裝和創建 Cloud Firestore 客戶端的更多信息,請參閱Cloud Firestore 客戶端庫

$query = $citiesRef->orderBy('name')->limit(3);
統一
Query query = citiesRef.OrderBy("Name").Limit(3);
C#
Query query = citiesRef.OrderBy("Name").Limit(3);
紅寶石
query = cities_ref.order("name").limit(3)

您還可以按降序排序以獲得最後3 個城市:

Web modular API

import { query, orderBy, limit } from "firebase/firestore";  

const q = query(citiesRef, orderBy("name", "desc"), limit(3));

Web namespaced API

citiesRef.orderBy("name", "desc").limit(3);
迅速
注意:此產品不適用於 watchOS 和 App Clip 目標。
citiesRef.order(by: "name", descending: true).limit(to: 3)
目標-C
注意:此產品不適用於 watchOS 和 App Clip 目標。
[[citiesRef queryOrderedByField:@"name" descending:YES] queryLimitedTo:3];

Kotlin+KTX

citiesRef.orderBy("name", Query.Direction.DESCENDING).limit(3)

Java

citiesRef.orderBy("name", Direction.DESCENDING).limit(3);

Dart

final citiesRef = db.collection("cities");
citiesRef.orderBy("name", descending: true).limit(3);
爪哇
Query query = cities.orderBy("name", Direction.DESCENDING).limit(3);
Python
cities_ref = db.collection('cities')
query = cities_ref.order_by(
    'name', direction=firestore.Query.DESCENDING).limit(3)
results = query.stream()

Python

cities_ref = db.collection("cities")
query = cities_ref.order_by("name", direction=firestore.Query.DESCENDING).limit(3)
results = query.stream()
C++
cities_ref.OrderBy("name", Query::Direction::kDescending).Limit(3);
節點.js
const lastThreeRes = await citiesRef.orderBy('name', 'desc').limit(3).get();
query := cities.OrderBy("name", firestore.Desc).Limit(3)
PHP

PHP

有關安裝和創建 Cloud Firestore 客戶端的更多信息,請參閱Cloud Firestore 客戶端庫

$query = $citiesRef->orderBy('name', 'DESC')->limit(3);
統一
Query query = citiesRef.OrderByDescending("Name").Limit(3);
C#
Query query = citiesRef.OrderByDescending("Name").Limit(3);
紅寶石
query = cities_ref.order("name", "desc").limit(3)

您還可以按多個字段排序。例如,如果您想按州排序,並在每個州內按人口降序排序:

Web modular API

import { query, orderBy } from "firebase/firestore";  

const q = query(citiesRef, orderBy("state"), orderBy("population", "desc"));

Web namespaced API

citiesRef.orderBy("state").orderBy("population", "desc");
迅速
注意:此產品不適用於 watchOS 和 App Clip 目標。
citiesRef
    .order(by: "state")
    .order(by: "population", descending: true)
目標-C
注意:此產品不適用於 watchOS 和 App Clip 目標。
[[citiesRef queryOrderedByField:@"state"] queryOrderedByField:@"population" descending:YES];

Kotlin+KTX

citiesRef.orderBy("state").orderBy("population", Query.Direction.DESCENDING)

Java

citiesRef.orderBy("state").orderBy("population", Direction.DESCENDING);

Dart

final citiesRef = db.collection("cities");
citiesRef.orderBy("state").orderBy("population", descending: true);
爪哇
Query query = cities.orderBy("state").orderBy("population", Direction.DESCENDING);
Python
cities_ref = db.collection('cities')
cities_ref.order_by('state').order_by(
    'population', direction=firestore.Query.DESCENDING)

Python

cities_ref = db.collection("cities")
cities_ref.order_by("state").order_by(
    "population", direction=firestore.Query.DESCENDING
)
C++
cities_ref.OrderBy("state").OrderBy("name", Query::Direction::kDescending);
節點.js
const byStateByPopRes = await citiesRef.orderBy('state').orderBy('population', 'desc').get();
query := client.Collection("cities").OrderBy("state", firestore.Asc).OrderBy("population", firestore.Desc)
PHP

PHP

有關安裝和創建 Cloud Firestore 客戶端的更多信息,請參閱Cloud Firestore 客戶端庫

$query = $citiesRef->orderBy('state')->orderBy('population', 'DESC');
統一
Query query = citiesRef.OrderBy("State").OrderByDescending("Population");
C#
Query query = citiesRef.OrderBy("State").OrderByDescending("Population");
紅寶石
query = cities_ref.order("state").order("population", "desc")

您可以將where()過濾器與orderBy()limit()結合使用。在下面的例子中,查詢定義了一個人口閾值,按人口升序排序,只返回前幾個超過閾值的結果:

Web modular API

import { query, where, orderBy, limit } from "firebase/firestore";  

const q = query(citiesRef, where("population", ">", 100000), orderBy("population"), limit(2));

Web namespaced API

citiesRef.where("population", ">", 100000).orderBy("population").limit(2);
迅速
注意:此產品不適用於 watchOS 和 App Clip 目標。
citiesRef
    .whereField("population", isGreaterThan: 100000)
    .order(by: "population")
    .limit(to: 2)
目標-C
注意:此產品不適用於 watchOS 和 App Clip 目標。
[[[citiesRef queryWhereField:@"population" isGreaterThan:@100000]
    queryOrderedByField:@"population"]
    queryLimitedTo:2];

Kotlin+KTX

citiesRef.whereGreaterThan("population", 100000).orderBy("population").limit(2)

Java

citiesRef.whereGreaterThan("population", 100000).orderBy("population").limit(2);

Dart

final citiesRef = db.collection("cities");
citiesRef
    .where("population", isGreaterThan: 100000)
    .orderBy("population")
    .limit(2);
爪哇
Query query = cities.whereGreaterThan("population", 2500000L).orderBy("population").limit(2);
Python
cities_ref = db.collection('cities')
query = cities_ref.where(
    'population', '>', 2500000).order_by('population').limit(2)
results = query.stream()

Python

cities_ref = db.collection("cities")
query = cities_ref.where("population", ">", 2500000).order_by("population").limit(2)
results = query.stream()
C++
cities_ref.WhereGreaterThan("population", FieldValue::Integer(100000))
    .OrderBy("population")
    .Limit(2);
節點.js
const biggestRes = await citiesRef.where('population', '>', 2500000)
  .orderBy('population').limit(2).get();
query := cities.Where("population", ">", 2500000).OrderBy("population", firestore.Desc).Limit(2)
PHP

PHP

有關安裝和創建 Cloud Firestore 客戶端的更多信息,請參閱Cloud Firestore 客戶端庫

$query = $citiesRef
    ->where('population', '>', 2500000)
    ->orderBy('population')
    ->limit(2);
統一
Query query = citiesRef
    .WhereGreaterThan("Population", 2500000)
    .OrderBy("Population")
    .Limit(2);
C#
Query query = citiesRef
    .WhereGreaterThan("Population", 2500000)
    .OrderBy("Population")
    .Limit(2);
紅寶石
query = cities_ref.where("population", ">", 2_500_000).order("population").limit(2)

但是,如果您有一個具有範圍比較( <<=>>= )的過濾器,您的第一次排序必須在同一字段上,請參閱下面的orderBy()限制列表。

限制

請注意orderBy()子句的以下限制:

  • orderBy()子句還過濾是否存在給定字段。結果集將不包括不包含給定字段的文檔。
  • 如果您包含一個帶有範圍比較的過濾器( <<=>>= ),您的第一個排序必須在同一個字段上:

    有效:同一字段上的範圍過濾器和orderBy

    Web modular API

    import { query, where, orderBy } from "firebase/firestore";  
    
    const q = query(citiesRef, where("population", ">", 100000), orderBy("population"));

    Web namespaced API

    citiesRef.where("population", ">", 100000).orderBy("population");
    迅速
    注意:此產品不適用於 watchOS 和 App Clip 目標。
    citiesRef
        .whereField("population", isGreaterThan: 100000)
        .order(by: "population")
    目標-C
    注意:此產品不適用於 watchOS 和 App Clip 目標。
    [[citiesRef queryWhereField:@"population" isGreaterThan:@100000]
        queryOrderedByField:@"population"];

    Kotlin+KTX

    citiesRef.whereGreaterThan("population", 100000).orderBy("population")

    Java

    citiesRef.whereGreaterThan("population", 100000).orderBy("population");

    Dart

    final citiesRef = db.collection("cities");
    citiesRef.where("population", isGreaterThan: 100000).orderBy("population");
    爪哇
    Query query = cities.whereGreaterThan("population", 2500000L).orderBy("population");
    Python
    cities_ref = db.collection('cities')
    query = cities_ref.where(
        'population', '>', 2500000).order_by('population')
    results = query.stream()

    Python

    cities_ref = db.collection("cities")
    query = cities_ref.where("population", ">", 2500000).order_by("population")
    results = query.stream()
    節點.js
    citiesRef.where('population', '>', 2500000).orderBy('population');
    query := cities.Where("population", ">", 2500000).OrderBy("population", firestore.Asc)
    PHP

    PHP

    有關安裝和創建 Cloud Firestore 客戶端的更多信息,請參閱Cloud Firestore 客戶端庫

    $query = $citiesRef
        ->where('population', '>', 2500000)
        ->orderBy('population');
    統一
    Query query = citiesRef
        .WhereGreaterThan("Population", 2500000)
        .OrderBy("Population");
    C#
    Query query = citiesRef
        .WhereGreaterThan("Population", 2500000)
        .OrderBy("Population");
    紅寶石
    query = cities_ref.where("population", ">", 2_500_000).order("population")

    無效:不同字段上的範圍過濾器和一階orderBy

    Web modular API

    import { query, where, orderBy } from "firebase/firestore";  
    
    const q = query(citiesRef, where("population", ">", 100000), orderBy("country"));

    Web namespaced API

    citiesRef.where("population", ">", 100000).orderBy("country");
    迅速
    注意:此產品不適用於 watchOS 和 App Clip 目標。
    citiesRef
        .whereField("population", isGreaterThan: 100000)
        .order(by: "country")
    目標-C
    注意:此產品不適用於 watchOS 和 App Clip 目標。
    [[citiesRef queryWhereField:@"population" isGreaterThan:@100000] queryOrderedByField:@"country"];

    Kotlin+KTX

    citiesRef.whereGreaterThan("population", 100000).orderBy("country")

    Java

    citiesRef.whereGreaterThan("population", 100000).orderBy("country");

    Dart

    final citiesRef = db.collection("cities");
    citiesRef.where("population", isGreaterThan: 100000).orderBy("country");
    爪哇
    Query query = cities.whereGreaterThan("population", 2500000L).orderBy("country");
    Python
    cities_ref = db.collection('cities')
    query = cities_ref.where('population', '>', 2500000).order_by('country')
    results = query.stream()

    Python

    cities_ref = db.collection("cities")
    query = cities_ref.where("population", ">", 2500000).order_by("country")
    results = query.stream()
    C++
    // BAD EXAMPLE -- will crash the program:
    cities_ref.WhereGreaterThan("population", FieldValue::Integer(100000))
        .OrderBy("country");
    節點.js
    citiesRef.where('population', '>', 2500000).orderBy('country');
    // Note: This is an invalid query. It violates the constraint that range
    // and order by are required to be on the same field.
    query := cities.Where("population", ">", 2500000).OrderBy("country", firestore.Asc)
    PHP

    PHP

    有關安裝和創建 Cloud Firestore 客戶端的更多信息,請參閱Cloud Firestore 客戶端庫

    $invalidRangeQuery = $citiesRef
        ->where('population', '>', 2500000)
        ->orderBy('country');
    統一
    Query query = citiesRef
        .WhereGreaterThan("Population", 2500000)
        .OrderBy("Country");
    C#
    Query query = citiesRef
        .WhereGreaterThan("Population", 2500000)
        .OrderBy("Country");
    紅寶石
    query = cities_ref.where("population", ">", 2_500_000).order("country")
  • 您不能按相等 ( = ) 或in中包含的任何字段對查詢進行排序。

orderBy和存在

當您按給定字段對查詢進行排序時,查詢只能返回存在排序字段的文檔。

例如,以下查詢不會返回任何未設置population字段的文檔,即使它們符合查詢過濾器。

爪哇
db.collection("cities").whereEqualTo("country", “USA”).orderBy(“population”);

一個相關的影響適用於不平等。在字段上使用不等式過濾器的查詢也意味著按該字段排序。以下查詢不會返回沒有population字段的文檔,即使該文檔中的country = USA也是如此。作為解決方法,您可以為每個排序執行單獨的查詢,或者您可以為您排序所依據的所有字段分配一個值。

爪哇
db.collection(“cities”).where(or(“country”, USA”), greaterThan(“population”, 250000));

上面的查詢包含對不等式的隱含排序,等同於以下內容:

爪哇
db.collection(“cities”).where(or(“country”, USA”), greaterThan(“population”, 250000)).orderBy(“population”);