Join us for Firebase Summit on November 10, 2021. Tune in to learn how Firebase can help you accelerate app development, release with confidence, and scale with ease. Register

Commandez et limitez les données avec Cloud Firestore

Cloud Firestore fournit une puissante fonctionnalité de requête pour spécifier les documents que vous souhaitez récupérer à partir d'une collection. Ces requêtes peuvent également être utilisés avec get() ou addSnapshotListener() , comme décrit dans Données .

Données de commande et de limite

Par défaut, une requête récupère tous les documents qui satisfont la requête dans l'ordre croissant par ID de document. Vous pouvez spécifier l'ordre de tri pour vos données à l' aide orderBy() , et vous pouvez limiter le nombre de documents récupérés en utilisant limit() .

Par exemple, vous pouvez rechercher les 3 premières villes par ordre alphabétique avec :

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);
Rapide
citiesRef.order(by: "name").limit(to: 3)
Objectif c
[[citiesRef queryOrderedByField:@"name"] queryLimitedTo:3];

Java

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

Kotlin+KTX

citiesRef.orderBy("name").limit(3)
Java
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);
Node.js
const firstThreeRes = await citiesRef.orderBy('name').limit(3).get();
Aller
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);
Rubis
query = cities_ref.order("name").limit(3)

Vous pourriez également trier par ordre décroissant pour obtenir les dernières 3 villes:

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);
Rapide
citiesRef.order(by: "name", descending: true).limit(to: 3)
Objectif c
[[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)
Java
Query query = cities.orderBy("name", Direction.DESCENDING).limit(3);
Python
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();
Aller
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);
Rubis
query = cities_ref.order("name", "desc").limit(3)

Vous pouvez également commander par plusieurs champs. Par exemple, si vous vouliez trier par état, et dans chaque état trier par population par ordre décroissant :

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");
Rapide
citiesRef
    .order(by: "state")
    .order(by: "population", descending: true)
Objectif c
[[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)
Java
Query query = cities.orderBy("state").orderBy("population", Direction.DESCENDING);
Python
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();
Aller
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");
Rubis
query = cities_ref.order("state").order("population", "desc")

Vous pouvez combiner where() filtres avec orderBy() et limit() . Dans l'exemple suivant, les requêtes définissent un seuil de population, trient par population dans l'ordre croissant et renvoient uniquement les premiers résultats qui dépassent le seuil :

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);
Rapide
citiesRef
    .whereField("population", isGreaterThan: 100000)
    .order(by: "population")
    .limit(to: 2)
Objectif c
[[[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)
Java
Query query = cities.whereGreaterThan("population", 2500000L).orderBy("population").limit(2);
Python
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();
Aller
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);
Rubis
query = cities_ref.where("population", ">", 2_500_000).order("population").limit(2)

Toutefois, si vous avez un filtre avec une comparaison de la plage ( < , <= , > , >= ), votre première commande doit être sur le même terrain, voir la liste des orderBy() les limites ci - dessous.

Limites

Notez les restrictions suivantes pour orderBy() clauses:

  • Un orderBy() clause filtre également pour l' existence des champs donnés. L'ensemble de résultats n'inclura pas les documents qui ne contiennent pas les champs donnés.
  • Si vous incluez un filtre avec une comparaison de la plage ( < , <= , > , >= ), votre première commande doit être sur le même terrain:

    Validité: filter et orderBy sur le même terrain

    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");
    Rapide
    citiesRef
        .whereField("population", isGreaterThan: 100000)
        .order(by: "population")
    Objectif c
    [[citiesRef queryWhereField:@"population" isGreaterThan:@100000]
        queryOrderedByField:@"population"];

    Java

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

    Kotlin+KTX

    citiesRef.whereGreaterThan("population", 100000).orderBy("population")
    Java
    Query query = cities.whereGreaterThan("population", 2500000L).orderBy("population");
    Python
    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');
    Aller
    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");
    Rubis
    query = cities_ref.where("population", ">", 2_500_000).order("population")

    Non valide: filter et le premier orderBy sur différents domaines

    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");
    Rapide
    citiesRef
        .whereField("population", isGreaterThan: 100000)
        .order(by: "country")
    Objectif c
    [[citiesRef queryWhereField:@"population" isGreaterThan:@100000] queryOrderedByField:@"country"];

    Java

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

    Kotlin+KTX

    citiesRef.whereGreaterThan("population", 100000).orderBy("country")
    Java
    Query query = cities.whereGreaterThan("population", 2500000L).orderBy("country");
    Python
    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');
    Aller
    // 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");
    Rubis
    query = cities_ref.where("population", ">", 2_500_000).order("country")
  • Vous ne pouvez pas commander votre requête par un champ inclus dans une égalité ( = ) ou in l' article.