Совокупность
Все агрегатные функции могут использоваться в качестве выражений верхнего уровня на этапе aggregate(...) .
| Имя | Описание |
COUNT | Возвращает количество документов. |
COUNT_IF | Возвращает количество документов, в которых выражение оценивается как TRUE |
COUNT_DISTINCT | Возвращает количество уникальных значений, не являющихся NULL |
SUM | Возвращает сумму всех NUMERIC значений. |
AVERAGE | Возвращает среднее значение всех NUMERIC значений. |
MINIMUM | Возвращает минимальное NULL значение. |
MAXIMUM | Возвращает максимальное значение, отличное от NULL |
FIRST | Возвращает значение expression для первого документа. |
LAST | Возвращает значение expression для последнего документа. |
ARRAY_AGG | Возвращает массив всех входных значений. |
ARRAY_AGG_DISTINCT | Возвращает массив всех уникальных входных значений. |
СЧИТАТЬ
Синтаксис:
count() -> INT64
count(expression: ANY) -> INT64
Описание:
Возвращает количество документов с предыдущего этапа, в которых expression принимает любое NULL значение. Если expression не указано, возвращает общее количество документов с предыдущего этапа.
Node.js
// Total number of books in the collection const countOfAll = await db.pipeline() .collection("books") .aggregate(countAll().as("count")) .execute(); // Number of books with nonnull `ratings` field const countField = await db.pipeline() .collection("books") .aggregate(field("ratings&q"count")) .execute();test.firestore.js
Web
// Total number of books in the collection const countOfAll = await execute(db.pipeline() .collection("books") .aggregate(countAll().as("count")) ); // Number of books with nonnull `ratings` field const countField = await execute(db.pipeline() .collection("books") .aggregate(field(&quocount().as("count")) );test.firestore.js
Быстрый
// Total number of books in the collection let countAll = try await db.pipeline() .collection("books") .aggregate([CountAll().as("count")]) .execute() // Number of books with nonnull `ratings` field let countField = try await db.pipeline() .collection("books") .aggregate([Field("ratings&q;count")]) .execute()PipelineSnippets.swift
Kotlin
// Total number of books in the collection val countAll = db.pipeline() .collection("books") .aggregate(AggregateFunction.countAll().alias("count")) .execute() // Number of books with nonnull `ratings` field val countField = db.pipeline() .collection("books") .aggregate(AggregateFunction.count("ratins("count")) .execute()DocSnippets.kt
Java
// Total number of books in the collection Task<Pipeline.Snapshot> countAll = db.pipeline() .collection("books") .aggregate(AggregateFunction.countAll().alias("count")) .execute(); // Number of books with nonnull <`ratings` field T>askPipeline.Snapshot countField = db.pipeline() .collection("books") .aggregate(AggregateFunction.count("ratingquot;count")) .execute();DocSnippets.java
Python
from google.cloud.firestore_v1.pipeline_expressions import Count # Total number of books in the collection count_all = ( client.pipeline().collection("books").aggregate(Count().as_("count")).execute() ) # Number of books with nonnull `ratings` field count_field = ( client.pipeline() .collection("books") .aggregate(Count("ratinunt")) .execute() )firestore_pipelines.py
Java
// Total number of books in the collection Pipeline.Snapshot countAll = firestore.pipeline().collection("books").aggregate(countAll().as("count")).execute().get(); // Number of books with nonnull `ratings` field Pipeline.Snapshot countField = firestore .pipeline() .collection("books") .aggregate(count("ratings").as(&quo .execute() .get();PipelineSnippets.java
COUNT_IF
Синтаксис:
count_if(expression: BOOLEAN) -> INT64
Описание:
Возвращает количество документов из предыдущего этапа, в которых expression принимает значение TRUE .
Node.js
const result = await db.pipeline() .collection("books") .aggregate( field("rating").greaterThan(4).countIf().as("filtered .execute();test.firestore.js
Web
const result = await execute(db.pipeline() .collection("books") .aggregate( field("rating").greaterThan(4).countIf().as(&ququot;) ) );test.firestore.js
Быстрый
let result = try await db.pipeline() .collection("books") .aggregate([ AggregateFunction("count_if", [Field("rating").greaterThan(4)]).as(&quo ]) .execute()PipelineSnippets.swift
Kotlin
val result = db.pipeline() .collection("books") .aggregate( AggregateFunction.countIf(field("rating").greaterThan(4)).alias("filteredCou) .execute()DocSnippets.kt
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("books") .aggregate( AggregateFunction.countIf(field("rating").greaterThan(4)).alias("filteredCoun .execute();DocSnippets.java
Python
from google.cloud.firestore_v1.pipeline_expressions import Field result = ( client.pipeline() .collection("books") .aggregate(Field.of("rating").greater_than(4).count_if().as_("filteredcute() )firestore_pipelines.py
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("books") .aggregate(countIf(field("rating").greaterThan(4)).as("filteredCount")) .get();PipelineSnippets.java
COUNT_DISTINCT
Синтаксис:
count_distinct(expression: ANY) -> INT64
Описание:
Возвращает количество уникальных значений expression , не являющихся NULL и не являющихся ABSENT .
Node.js
const result = await db.pipeline() .collection("books") .aggregate(field("author").countDistinct().as("unique .execute();test.firestore.js
Web
const result = await execute(db.pipeline() .collection("books") .aggregate(field("author").countDistinct().as(&rs")) );test.firestore.js
Быстрый
let result = try await db.pipeline() .collection("books") .aggregate([AggregateFunction("count_distinct", [Field("author")]).as(&qt;)]) .execute()PipelineSnippets.swift
Kotlin
val result = db.pipeline() .collection("books") .aggregate(AggregateFunction.countDistinct("author").alias("unique_) .execute()DocSnippets.kt
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("books") .aggregate(AggregateFunction.countDistinct("author").alias("unique_a .execute();DocSnippets.java
Python
from google.cloud.firestore_v1.pipeline_expressions import Field result = ( client.pipeline() .collection("books") .aggregate(Field.of("author").count_distinct().as_("unique_aucute() )firestore_pipelines.py
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("books") .aggregate(countDistinct("author").as("unique_authors")) .get();PipelineSnippets.java
СУММА
Синтаксис:
sum(expression: ANY) -> NUMBER
Описание:
Возвращает сумму всех числовых значений, игнорируя нечисловые. Возвращает NaN если хотя бы одно значение является NaN .
Выходные данные будут иметь тот же тип, что и входные данные самого широкого типа, за исключением следующих случаев:
- Если
INTEGERне может быть представлен какINTEGER, он будет преобразован в тип данныхDOUBLE.
Node.js
const result = await db.pipeline() .collection("cities") .aggregate(field("population").sum().as("totalPo .execute();test.firestore.js
Web
const result = await execute(db.pipeline() .collection("cities") .aggregate(field("population").sum().as(&qon")) );test.firestore.js
Быстрый
let result = try await db.pipeline() .collection("cities") .aggregate([Field("population").sum().as("totalPoxecute()PipelineSnippets.swift
Kotlin
val result = db.pipeline() .collection("cities") .aggregate(AggregateFunction.sum("population").alias("totalPop) .execute()DocSnippets.kt
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("cities") .aggregate(AggregateFunction.sum("population").alias("totalPopu .execute();DocSnippets.java
Python
from google.cloud.firestore_v1.pipeline_expressions import Field result = ( client.pipeline() .collection("cities") .aggregate(Field.of("population").sum().as_("totalPopulcute() )firestore_pipelines.py
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("cities") .aggregate(sum("population").as("totalPopulation")) .get();PipelineSnippets.java
СРЕДНИЙ
Синтаксис:
average(expression: ANY) -> FLOAT64
Описание:
Возвращает среднее значение для всех числовых значений, игнорируя нечисловые. Если какое-либо значение равно NaN , результат будет NaN , а если числовые значения не суммированы, результат будет NULL .
Выходные данные будут иметь тот же тип, что и входные, за исключением следующих случаев:
- Если
INTEGERне может быть представлен какINTEGER, он будет преобразован в тип данныхDOUBLE.
Node.js
const result = await db.pipeline() .collection("cities") .aggregate(field("population").average().as("averagePo .execute();test.firestore.js
Web
const result = await execute(db.pipeline() .collection("cities") .aggregate(field("population").average().as(&quoon")) );test.firestore.js
Быстрый
let result = try await db.pipeline() .collection("cities") .aggregate([Field("population").average().as("averagePoxecute()PipelineSnippets.swift
Kotlin
val result = db.pipeline() .collection("cities") .aggregate(AggregateFunction.average("population").alias("averagePop) .execute()DocSnippets.kt
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("cities") .aggregate(AggregateFunction.average("population").alias("averagePopu .execute();DocSnippets.java
Python
from google.cloud.firestore_v1.pipeline_expressions import Field result = ( client.pipeline() .collection("cities") .aggregate(Field.of("population").average().as_("averagePopulcute() )firestore_pipelines.py
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("cities") .aggregate(average("population").as("averagePopulation")) .get();PipelineSnippets.java
МИНИМУМ
Синтаксис:
minimum(expression: ANY) -> ANY
Описание:
Возвращает минимальное NULL (неотсутствующее) значение expression при его оценке для каждого документа.
Если отсутствуют значения, отличные от NULL , возвращается NULL . Это относится и к случаям, когда документы не рассматриваются.
Если существует несколько минимальных эквивалентных значений, может быть возвращено любое из этих значений. Порядок типов значений соответствует документированному порядку .
Node.js
const result = await db.pipeline() .collection("books") .aggregate(field("price").minimum().as("mini .execute();test.firestore.js
Web
const result = await execute(db.pipeline() .collection("books") .aggregate(field("price").minimum().asce")) );test.firestore.js
Быстрый
let result = try await db.pipeline() .collection("books") .aggregate([Field("price").minimum().as("minixecute()PipelineSnippets.swift
Kotlin
val result = db.pipeline() .collection("books") .aggregate(AggregateFunction.minimum("price").alias("minim) .execute()DocSnippets.kt
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("books") .aggregate(AggregateFunction.minimum("price").alias("minimu .execute();DocSnippets.java
Python
from google.cloud.firestore_v1.pipeline_expressions import Field result = ( client.pipeline() .collection("books") .aggregate(Field.of("price").minimum().as_("minimumcute() )firestore_pipelines.py
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("books") .aggregate(minimum("price").as("minimumPrice")) .get();PipelineSnippets.java
МАКСИМУМ
Синтаксис:
maximum(expression: ANY) -> ANY
Описание:
Возвращает максимальное NULL (неотсутствующее) значение expression при его оценке для каждого документа.
Если отсутствуют значения, отличные от NULL , возвращается NULL . Это относится и к случаям, когда документы не рассматриваются.
Если существует несколько максимальных эквивалентных значений, может быть возвращено любое из этих значений. Порядок типов значений соответствует документированному порядку .
Node.js
const result = await db.pipeline() .collection("books") .aggregate(field("price").maximum().as("maxi .execute();test.firestore.js
Web
const result = await execute(db.pipeline() .collection("books") .aggregate(field("price").maximum().asce")) );test.firestore.js
Быстрый
let result = try await db.pipeline() .collection("books") .aggregate([Field("price").maximum().as("maxixecute()PipelineSnippets.swift
Kotlin
val result = db.pipeline() .collection("books") .aggregate(AggregateFunction.maximum("price").alias("maxim) .execute()DocSnippets.kt
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("books") .aggregate(AggregateFunction.maximum("price").alias("maximu .execute();DocSnippets.java
Python
from google.cloud.firestore_v1.pipeline_expressions import Field result = ( client.pipeline() .collection("books") .aggregate(Field.of("price").maximum().as_("maximumcute() )firestore_pipelines.py
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("books") .aggregate(maximum("price").as("maximumPrice")) .get();PipelineSnippets.java
ПЕРВЫЙ
Синтаксис:
first(expression: ANY) -> ANY
Описание:
Возвращает значение expression для первого возвращенного документа.
ПОСЛЕДНИЙ
Синтаксис:
last(expression: ANY) -> ANY
Описание:
Возвращает значение expression для последнего возвращенного документа.
ARRAY_AGG
Синтаксис:
array_agg(expression: ANY) -> ARRAY<ANY>
Описание:
Возвращает массив, содержащий все значения expression , вычисленные для каждого документа.
Если выражение принимает значение, отсутствующее в исходном виде, оно преобразуется в NULL .
Порядок элементов в выходном массиве нестабилен, и на него не следует полагаться.
ARRAY_AGG_DISTINCT
Синтаксис:
array_agg_distinct(expression: ANY) -> ARRAY<ANY>
Описание:
Возвращает массив, содержащий все уникальные значения expression , вычисленные для каждого документа.
Если выражение принимает значение, отсутствующее в исходном виде, оно преобразуется в NULL .
Порядок элементов в выходном массиве нестабилен, и на него не следует полагаться.