Cloud Firestore предоставляет мощные функциональные возможности запросов для указания, какие документы вы хотите получить из коллекции. Эти запросы также можно использовать с get()
или addSnapshotListener()
, как описано в addSnapshotListener()
Получение данных .
Данные для заказа и лимита
По умолчанию запрос извлекает все документы, удовлетворяющие запросу, в порядке возрастания по идентификатору документа. Вы можете указать порядок сортировки данных с помощью orderBy()
, а также ограничить количество документов, извлекаемых с помощью limit()
.
Например, вы можете запросить первые 3 города в алфавитном порядке с помощью:
Интернет
citiesRef.orderBy("name").limit(3);
Быстрый
citiesRef.order(by: "name").limit(to: 3)
Цель-C
[[citiesRef queryOrderedByField:@"name"] queryLimitedTo:3];
Ява
citiesRef.orderBy("name").limit(3);
Котлин + KTX
citiesRef.orderBy("name").limit(3)
Ява
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();
Идти
query := cities.OrderBy("name", firestore.Asc).Limit(3)
PHP
$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 города:
Интернет
citiesRef.orderBy("name", "desc").limit(3);
Быстрый
citiesRef.order(by: "name", descending: true).limit(to: 3)
Цель-C
[[citiesRef queryOrderedByField:@"name" descending:YES] queryLimitedTo:3];
Ява
citiesRef.orderBy("name", Direction.DESCENDING).limit(3);
Котлин + KTX
citiesRef.orderBy("name", Query.Direction.DESCENDING).limit(3)
Ява
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();
Идти
query := cities.OrderBy("name", firestore.Desc).Limit(3)
PHP
$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)
Вы также можете заказать по нескольким полям. Например, если вы хотите упорядочить по штатам, а внутри каждого штата - по численности населения в порядке убывания:
Интернет
citiesRef.orderBy("state").orderBy("population", "desc");
Быстрый
citiesRef .order(by: "state") .order(by: "population", descending: true)
Цель-C
[[citiesRef queryOrderedByField:@"state"] queryOrderedByField:@"population" descending:YES];
Ява
citiesRef.orderBy("state").orderBy("population", Direction.DESCENDING);
Котлин + KTX
citiesRef.orderBy("state").orderBy("population", Query.Direction.DESCENDING)
Ява
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();
Идти
query := client.Collection("cities").OrderBy("state", firestore.Asc).OrderBy("population", firestore.Desc)
PHP
$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()
. В следующем примере запросы определяют порог совокупности, сортируют по совокупности в возрастающем порядке и возвращают только первые несколько результатов, превышающих порог:
Интернет
citiesRef.where("population", ">", 100000).orderBy("population").limit(2);
Быстрый
citiesRef .whereField("population", isGreaterThan: 100000) .order(by: "population") .limit(to: 2)
Цель-C
[[[citiesRef queryWhereField:@"population" isGreaterThan:@100000] queryOrderedByField:@"population"] queryLimitedTo:2];
Ява
citiesRef.whereGreaterThan("population", 100000).orderBy("population").limit(2);
Котлин + KTX
citiesRef.whereGreaterThan("population", 100000).orderBy("population").limit(2)
Ява
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();
Идти
query := cities.Where("population", ">", 2500000).OrderBy("population", firestore.Desc).Limit(2)
PHP
$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
по одному иorderBy
же полю.Интернет
citiesRef.where("population", ">", 100000).orderBy("population");
Быстрый
citiesRef .whereField("population", isGreaterThan: 100000) .order(by: "population")
Цель-C
[[citiesRef queryWhereField:@"population" isGreaterThan:@100000] queryOrderedByField:@"population"];
Ява
citiesRef.whereGreaterThan("population", 100000).orderBy("population");
Котлин + KTX
citiesRef.whereGreaterThan("population", 100000).orderBy("population")
Ява
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');
Идти
query := cities.Where("population", ">", 2500000).OrderBy("population", firestore.Asc)
PHP
$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")
Invalid : Range filter и first
orderBy
для разных полейИнтернет
citiesRef.where("population", ">", 100000).orderBy("country");
Быстрый
citiesRef .whereField("population", isGreaterThan: 100000) .order(by: "country")
Цель-C
[[citiesRef queryWhereField:@"population" isGreaterThan:@100000] queryOrderedByField:@"country"];
Ява
citiesRef.whereGreaterThan("population", 100000).orderBy("country");
Котлин + KTX
citiesRef.whereGreaterThan("population", 100000).orderBy("country")
Ява
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');
Идти
// 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');
Единство
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
предложение.