Ordena y limita datos

Firestore proporciona una potente función de consulta para especificar qué documentos deseas recuperar de una colección. Estas consultas también se pueden usar con get() o addSnapshotListener(), como se describe en Obtén datos.

Ordena y limita los datos

Según la configuración predeterminada, una consulta recupera todos los documentos que corresponden con la consulta en orden ascendente por ID de documento. Puedes especificar el orden de clasificación para los datos que usan orderBy() y, con limit(), puedes limitar la cantidad de documentos recuperados.

Por ejemplo, puedes realizar una consulta que te muestre las primeras 3 ciudades en orden alfabético con:

Web
citiesRef.orderBy("name").limit(3)
Swift
citiesRef.order(by: "name").limit(to: 3)
Objective-C
[[citiesRef queryOrderedByField:@"name"] queryLimitedTo:3];
  
Java
Android
citiesRef.orderBy("name").limit(3);
Kotlin+KTX
Android
citiesRef.orderBy("name").limit(3)
Java
Query query = cities.orderBy("name").limit(3);
Query query = cities.orderBy("name").limitToLast(3);
Python
db.collection(u'cities').order_by(u'name').limit(3).stream()
C++
cities_ref.OrderBy("name").Limit(3);
  
Node.js
const firstThreeRes = await citiesRef.orderBy('name').limit(3).get();
Go
query := cities.OrderBy("name", firestore.Asc).Limit(3)
PHP
$query = $citiesRef->orderBy('name')->limit(3);
Unity
Query query = citiesRef.OrderBy("Name").Limit(3);
C#
Query query = citiesRef.OrderBy("Name").Limit(3);
Ruby
query = cities_ref.order("name").limit(3)

También puedes ordenar de forma descendente para ver las últimas 3 ciudades:

Web
citiesRef.orderBy("name", "desc").limit(3)
Swift
citiesRef.order(by: "name", descending: true).limit(to: 3)
Objective-C
[[citiesRef queryOrderedByField:@"name" descending:YES] queryLimitedTo:3];
  
Java
Android
citiesRef.orderBy("name", Direction.DESCENDING).limit(3);
Kotlin+KTX
Android
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()
C++
cities_ref.OrderBy("name", Query::Direction::kDescending).Limit(3);
  
Node.js
const lastThreeRes = await citiesRef.orderBy('name', 'desc').limit(3).get();
Go
query := cities.OrderBy("name", firestore.Desc).Limit(3)
PHP
$query = $citiesRef->orderBy('name', 'DESC')->limit(3);
Unity
Query query = citiesRef.OrderByDescending("Name").Limit(3);
C#
Query query = citiesRef.OrderByDescending("Name").Limit(3);
Ruby
query = cities_ref.order("name", "desc").limit(3)

También puedes ordenar según varios campos. Por ejemplo, si deseas ordenar por estado y, dentro de cada estado, por población de manera descendente:

Web
citiesRef.orderBy("state").orderBy("population", "desc")
Swift
citiesRef
    .order(by: "state")
    .order(by: "population", descending: true)
Objective-C
[[citiesRef queryOrderedByField:@"state"] queryOrderedByField:@"population" descending:YES];
  
Java
Android
citiesRef.orderBy("state").orderBy("population", Direction.DESCENDING);
Kotlin+KTX
Android
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)
C++
cities_ref.OrderBy("state").OrderBy("name", Query::Direction::kDescending);
  
Node.js
const byStateByPopRes = await citiesRef.orderBy('state').orderBy('population', 'desc').get();
Go
query := client.Collection("cities").OrderBy("state", firestore.Asc).OrderBy("population", firestore.Desc)
PHP
$query = $citiesRef->orderBy('state')->orderBy('population', 'DESC');
Unity
Query query = citiesRef.OrderBy("State").OrderByDescending("Population");
C#
Query query = citiesRef.OrderBy("State").OrderByDescending("Population");
Ruby
query = cities_ref.order("state").order("population", "desc")

Puedes combinar filtros where() con orderBy() y limit(). En el ejemplo siguiente, las consultas definen un umbral de población, clasifican por población en orden ascendente y muestran solo los primeros resultados que superan el umbral:

Web
citiesRef.where("population", ">", 100000).orderBy("population").limit(2)
Swift
citiesRef
    .whereField("population", isGreaterThan: 100000)
    .order(by: "population")
    .limit(to: 2)
Objective-C
[[[citiesRef queryWhereField:@"population" isGreaterThan:@100000]
    queryOrderedByField:@"population"]
    queryLimitedTo:2];
  
Java
Android
citiesRef.whereGreaterThan("population", 100000).orderBy("population").limit(2);
Kotlin+KTX
Android
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()
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();
Go
query := cities.Where("population", ">", 2500000).OrderBy("population", firestore.Desc).Limit(2)
PHP
$query = $citiesRef
    ->where('population', '>', 2500000)
    ->orderBy('population')
    ->limit(2);
Unity
Query query = citiesRef
    .WhereGreaterThan("Population", 2500000)
    .OrderBy("Population")
    .Limit(2);
C#
Query query = citiesRef
    .WhereGreaterThan("Population", 2500000)
    .OrderBy("Population")
    .Limit(2);
Ruby
query = cities_ref.where("population", ">", 2_500_000).order("population").limit(2)

Sin embargo, si tienes un filtro con una comparación de rangos (<, <=, > y >=), el primer ordenamiento debe estar en el mismo campo, consulta la lista de limitaciones de orderBy() a continuación.

Limitaciones

Ten en cuenta las siguientes restricciones para las cláusulas orderBy():

  • Una cláusula orderBy() también filtra en busca de los campos especificados. El conjunto de resultados no incluirá documentos que no contengan los campos correspondientes.
  • Si incluyes un filtro con una comparación de rangos (<, <=, > y >=), el primer ordenamiento debe estar en el mismo campo:

    Válido: Filtro de rango y orderBy en el mismo campo

    Web
    citiesRef.where("population", ">", 100000).orderBy("population")
    
    Swift
    citiesRef
        .whereField("population", isGreaterThan: 100000)
        .order(by: "population")
    
    Objective-C
    [[citiesRef queryWhereField:@"population" isGreaterThan:@100000]
        queryOrderedByField:@"population"];
      
    Java
    Android
    citiesRef.whereGreaterThan("population", 100000).orderBy("population");
    Kotlin+KTX
    Android
    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()
    
    Node.js
    citiesRef.where('population', '>', 2500000).orderBy('population');
    
    Go
    query := cities.Where("population", ">", 2500000).OrderBy("population", firestore.Asc)
    
    PHP
    $query = $citiesRef
        ->where('population', '>', 2500000)
        ->orderBy('population');
    
    Unity
    Query query = citiesRef
        .WhereGreaterThan("Population", 2500000)
        .OrderBy("Population");
    
    C#
    Query query = citiesRef
        .WhereGreaterThan("Population", 2500000)
        .OrderBy("Population");
    
    Ruby
    query = cities_ref.where("population", ">", 2_500_000).order("population")
    

    No válido: Filtro de rango y primer orderBy en campos distintos

    Web
    citiesRef.where("population", ">", 100000).orderBy("country")
    
    Swift
    citiesRef
        .whereField("population", isGreaterThan: 100000)
        .order(by: "country")
    
    Objective-C
    [[citiesRef queryWhereField:@"population" isGreaterThan:@100000] queryOrderedByField:@"country"];
      
    Java
    Android
    citiesRef.whereGreaterThan("population", 100000).orderBy("country");
    Kotlin+KTX
    Android
    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()
    
    C++
    // BAD EXAMPLE -- will crash the program:
    cities_ref.WhereGreaterThan("population", FieldValue::Integer(100000))
        .OrderBy("country");
      
    Node.js
    citiesRef.where('population', '>', 2500000).orderBy('country');
    
    Go
    // 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
    $query = $citiesRef
        ->where('population', '>', 2500000)
        ->orderBy('country');
    
    Unity
    Query query = citiesRef
        .WhereGreaterThan("Population", 2500000)
        .OrderBy("Country");
    
    C#
    Query query = citiesRef
        .WhereGreaterThan("Population", 2500000)
        .OrderBy("Country");
    
    Ruby
    query = cities_ref.where("population", ">", 2_500_000).order("country")
    
  • No puedes ordenar la consulta según ningún campo incluido en una cláusula de igualdad (=) o in.