Ordina e limita i dati con Cloud Firestore

Cloud Firestore fornisce una potente funzionalità di query per specificare quali documenti desideri recuperare da una raccolta. Queste query possono essere usate anche con get() o addSnapshotListener() , come descritto in Get Data .

Ordinare e limitare i dati

Per impostazione predefinita, una query recupera tutti i documenti che soddisfano la query in ordine crescente in base all'ID documento. Puoi specificare l'ordinamento per i tuoi dati usando orderBy() e puoi limitare il numero di documenti recuperati usando limit() .

Ad esempio, puoi interrogare le prime 3 città in ordine alfabetico con:

Web version 9

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

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

Web version 8

citiesRef.orderBy("name").limit(3);
Veloce
Nota: questo prodotto non è disponibile sui target watchOS e App Clip.
citiesRef.order(by: "name").limit(to: 3)
Obiettivo-C
Nota: questo prodotto non è disponibile sui target watchOS e App Clip.
[[citiesRef queryOrderedByField:@"name"] queryLimitedTo:3];

Java

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

Kotlin+KTX

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

Dart

final citiesRef = db.collection("cities");
citiesRef.orderBy("name").limit(3);
Giava
Query query = cities.orderBy("name").limit(3);
Query query = cities.orderBy("name").limitToLast(3);
Pitone
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);
Node.js
const firstThreeRes = await citiesRef.orderBy('name').limit(3).get();
andare
query := cities.OrderBy("name", firestore.Asc).Limit(3)
query := cities.OrderBy("name", firestore.Asc).LimitToLast(3)
PHP
$query = $citiesRef->orderBy('name')->limit(3);
Unità
Query query = citiesRef.OrderBy("Name").Limit(3);
C#
Query query = citiesRef.OrderBy("Name").Limit(3);
Rubino
query = cities_ref.order("name").limit(3)

Puoi anche ordinare in ordine decrescente per ottenere le ultime 3 città:

Web version 9

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

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

Web version 8

citiesRef.orderBy("name", "desc").limit(3);
Veloce
Nota: questo prodotto non è disponibile sui target watchOS e App Clip.
citiesRef.order(by: "name", descending: true).limit(to: 3)
Obiettivo-C
Nota: questo prodotto non è disponibile sui target watchOS e App Clip.
[[citiesRef queryOrderedByField:@"name" descending:YES] queryLimitedTo:3];

Java

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

Kotlin+KTX

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

Dart

final citiesRef = db.collection("cities");
citiesRef.orderBy("name", descending: true).limit(3);
Giava
Query query = cities.orderBy("name", Direction.DESCENDING).limit(3);
Pitone
cities_ref = db.collection(u'cities')
query = cities_ref.order_by(
    u'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);
Node.js
const lastThreeRes = await citiesRef.orderBy('name', 'desc').limit(3).get();
andare
query := cities.OrderBy("name", firestore.Desc).Limit(3)
PHP
$query = $citiesRef->orderBy('name', 'DESC')->limit(3);
Unità
Query query = citiesRef.OrderByDescending("Name").Limit(3);
C#
Query query = citiesRef.OrderByDescending("Name").Limit(3);
Rubino
query = cities_ref.order("name", "desc").limit(3)

Puoi anche ordinare per più campi. Ad esempio, se desideri ordinare per stato e all'interno di ogni stato ordina per popolazione in ordine decrescente:

Web version 9

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

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

Web version 8

citiesRef.orderBy("state").orderBy("population", "desc");
Veloce
Nota: questo prodotto non è disponibile sui target watchOS e App Clip.
citiesRef
    .order(by: "state")
    .order(by: "population", descending: true)
Obiettivo-C
Nota: questo prodotto non è disponibile sui target watchOS e App Clip.
[[citiesRef queryOrderedByField:@"state"] queryOrderedByField:@"population" descending:YES];

Java

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

Kotlin+KTX

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

Dart

final citiesRef = db.collection("cities");
citiesRef.orderBy("state").orderBy("population", descending: true);
Giava
Query query = cities.orderBy("state").orderBy("population", Direction.DESCENDING);
Pitone
cities_ref = db.collection(u'cities')
cities_ref.order_by(u'state').order_by(
    u'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);
Node.js
const byStateByPopRes = await citiesRef.orderBy('state').orderBy('population', 'desc').get();
andare
query := client.Collection("cities").OrderBy("state", firestore.Asc).OrderBy("population", firestore.Desc)
PHP
$query = $citiesRef->orderBy('state')->orderBy('population', 'DESC');
Unità
Query query = citiesRef.OrderBy("State").OrderByDescending("Population");
C#
Query query = citiesRef.OrderBy("State").OrderByDescending("Population");
Rubino
query = cities_ref.order("state").order("population", "desc")

Puoi combinare i filtri where( where() con orderBy() e limit() . Nell'esempio seguente, le query definiscono una soglia di popolazione, ordinano per popolazione in ordine crescente e restituiscono solo i primi risultati che superano la soglia:

Web version 9

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

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

Web version 8

citiesRef.where("population", ">", 100000).orderBy("population").limit(2);
Veloce
Nota: questo prodotto non è disponibile sui target watchOS e App Clip.
citiesRef
    .whereField("population", isGreaterThan: 100000)
    .order(by: "population")
    .limit(to: 2)
Obiettivo-C
Nota: questo prodotto non è disponibile sui target watchOS e App Clip.
[[[citiesRef queryWhereField:@"population" isGreaterThan:@100000]
    queryOrderedByField:@"population"]
    queryLimitedTo:2];

Java

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

Kotlin+KTX

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

Dart

final citiesRef = db.collection("cities");
citiesRef
    .where("population", isGreaterThan: 100000)
    .orderBy("population")
    .limit(2);
Giava
Query query = cities.whereGreaterThan("population", 2500000L).orderBy("population").limit(2);
Pitone
cities_ref = db.collection(u'cities')
query = cities_ref.where(
    u'population', u'>', 2500000).order_by(u'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);
Node.js
const biggestRes = await citiesRef.where('population', '>', 2500000)
  .orderBy('population').limit(2).get();
andare
query := cities.Where("population", ">", 2500000).OrderBy("population", firestore.Desc).Limit(2)
PHP
$query = $citiesRef
    ->where('population', '>', 2500000)
    ->orderBy('population')
    ->limit(2);
Unità
Query query = citiesRef
    .WhereGreaterThan("Population", 2500000)
    .OrderBy("Population")
    .Limit(2);
C#
Query query = citiesRef
    .WhereGreaterThan("Population", 2500000)
    .OrderBy("Population")
    .Limit(2);
Rubino
query = cities_ref.where("population", ">", 2_500_000).order("population").limit(2)

Tuttavia, se si dispone di un filtro con un confronto di intervallo ( < , <= , > , >= ), il primo ordinamento deve essere nello stesso campo, vedere l'elenco delle limitazioni orderBy() di seguito.

Limitazioni

Nota le seguenti restrizioni per le clausole orderBy() :

  • Una clausola orderBy() filtra anche l'esistenza dei campi dati. Il set di risultati non includerà i documenti che non contengono i campi specificati.
  • Se includi un filtro con un confronto di intervallo ( < , <= , > , >= ), il tuo primo ordine deve essere nello stesso campo:

    Valido : filtro intervallo e orderBy sullo stesso campo

    Web version 9

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

    Web version 8

    citiesRef.where("population", ">", 100000).orderBy("population");
    Veloce
    Nota: questo prodotto non è disponibile sui target watchOS e App Clip.
    citiesRef
        .whereField("population", isGreaterThan: 100000)
        .order(by: "population")
    Obiettivo-C
    Nota: questo prodotto non è disponibile sui target watchOS e App Clip.
    [[citiesRef queryWhereField:@"population" isGreaterThan:@100000]
        queryOrderedByField:@"population"];

    Java

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

    Kotlin+KTX

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

    Dart

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

    Python

    cities_ref = db.collection("cities")
    query = cities_ref.where("population", ">", 2500000).order_by("population")
    results = query.stream()
    Node.js
    citiesRef.where('population', '>', 2500000).orderBy('population');
    andare
    query := cities.Where("population", ">", 2500000).OrderBy("population", firestore.Asc)
    PHP
    $query = $citiesRef
        ->where('population', '>', 2500000)
        ->orderBy('population');
    Unità
    Query query = citiesRef
        .WhereGreaterThan("Population", 2500000)
        .OrderBy("Population");
    C#
    Query query = citiesRef
        .WhereGreaterThan("Population", 2500000)
        .OrderBy("Population");
    Rubino
    query = cities_ref.where("population", ">", 2_500_000).order("population")

    Non valido : filtro intervallo e first orderBy su campi diversi

    Web version 9

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

    Web version 8

    citiesRef.where("population", ">", 100000).orderBy("country");
    Veloce
    Nota: questo prodotto non è disponibile sui target watchOS e App Clip.
    citiesRef
        .whereField("population", isGreaterThan: 100000)
        .order(by: "country")
    Obiettivo-C
    Nota: questo prodotto non è disponibile sui target watchOS e App Clip.
    [[citiesRef queryWhereField:@"population" isGreaterThan:@100000] queryOrderedByField:@"country"];

    Java

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

    Kotlin+KTX

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

    Dart

    final citiesRef = db.collection("cities");
    citiesRef.where("population", isGreaterThan: 100000).orderBy("country");
    Giava
    Query query = cities.whereGreaterThan("population", 2500000L).orderBy("country");
    Pitone
    cities_ref = db.collection(u'cities')
    query = cities_ref.where(u'population', u'>', 2500000).order_by(u'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");
    Node.js
    citiesRef.where('population', '>', 2500000).orderBy('country');
    andare
    // 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
    $invalidRangeQuery = $citiesRef
        ->where('population', '>', 2500000)
        ->orderBy('country');
    Unità
    Query query = citiesRef
        .WhereGreaterThan("Population", 2500000)
        .OrderBy("Country");
    C#
    Query query = citiesRef
        .WhereGreaterThan("Population", 2500000)
        .OrderBy("Country");
    Rubino
    query = cities_ref.where("population", ">", 2_500_000).order("country")
  • Non puoi ordinare la tua query in base a nessun campo incluso in un'uguaglianza ( = ) o in una clausola.