Aggregate
Todas as funções de agregação podem ser usadas como expressões de nível superior na etapa aggregate(...).
| Nome | Descrição |
COUNT
|
Retorna o número de documentos. |
COUNT_IF
|
Retorna a contagem de documentos em que uma expressão é avaliada como TRUE.
|
COUNT_DISTINCT
|
Retorna a contagem de valores exclusivos e diferentes de NULL.
|
SUM
|
Retorna a soma de todos os valores de NUMERIC
|
AVERAGE
|
Retorna a média de todos os valores de NUMERIC.
|
MINIMUM
|
Retorna o valor mínimo diferente de NULL.
|
MAXIMUM
|
Retorna o valor máximo não NULL
|
FIRST
|
Retorna o valor expression do primeiro documento.
|
LAST
|
Retorna o valor expression do último documento.
|
ARRAY_AGG
|
Retorna uma matriz de todos os valores de entrada. |
ARRAY_AGG_DISTINCT
|
Retorna uma matriz de todos os valores de entrada distintos. |
COUNT
Sintaxe:
count() -> INT64
count(expression: ANY) -> INT64
Descrição:
Retorna a contagem de documentos da etapa anterior em que expression é avaliado como qualquer valor diferente de NULL. Se nenhum expression for fornecido, vai retornar a contagem total de documentos da etapa anterior.
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").count().as("count")) .execute();
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("ratings").count().as("count")) );
Swift
// 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").count().as("count")]) .execute()
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("ratings").alias("count")) .execute()
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 Task<Pipeline.Snapshot> countField = db.pipeline() .collection("books") .aggregate(AggregateFunction.count("ratings").alias("count")) .execute();
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("ratings").as_("count")) .execute() )
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("count")) .execute() .get();
COUNT_IF
Sintaxe:
count_if(expression: BOOLEAN) -> INT64
Descrição:
Retorna o número de documentos da etapa anterior em que expression é avaliado como TRUE.
Node.js
const result = await db.pipeline() .collection("books") .aggregate( field("rating").greaterThan(4).countIf().as("filteredCount") ) .execute();
Web
const result = await execute(db.pipeline() .collection("books") .aggregate( field("rating").greaterThan(4).countIf().as("filteredCount") ) );
Swift
let result = try await db.pipeline() .collection("books") .aggregate([ AggregateFunction("count_if", [Field("rating").greaterThan(4)]).as("filteredCount") ]) .execute()
Kotlin
val result = db.pipeline() .collection("books") .aggregate( AggregateFunction.countIf(field("rating").greaterThan(4)).alias("filteredCount") ) .execute()
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("books") .aggregate( AggregateFunction.countIf(field("rating").greaterThan(4)).alias("filteredCount") ) .execute();
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_("filteredCount")) .execute() )
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("books") .aggregate(countIf(field("rating").greaterThan(4)).as("filteredCount")) .execute() .get();
COUNT_DISTINCT
Sintaxe:
count_distinct(expression: ANY) -> INT64
Descrição:
Retorna o número de valores não NULL e não ABSENT exclusivos de expression.
Node.js
const result = await db.pipeline() .collection("books") .aggregate(field("author").countDistinct().as("unique_authors")) .execute();
Web
const result = await execute(db.pipeline() .collection("books") .aggregate(field("author").countDistinct().as("unique_authors")) );
Swift
let result = try await db.pipeline() .collection("books") .aggregate([AggregateFunction("count_distinct", [Field("author")]).as("unique_authors")]) .execute()
Kotlin
val result = db.pipeline() .collection("books") .aggregate(AggregateFunction.countDistinct("author").alias("unique_authors")) .execute()
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("books") .aggregate(AggregateFunction.countDistinct("author").alias("unique_authors")) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field result = ( client.pipeline() .collection("books") .aggregate(Field.of("author").count_distinct().as_("unique_authors")) .execute() )
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("books") .aggregate(countDistinct("author").as("unique_authors")) .execute() .get();
SUM
Sintaxe:
sum(expression: ANY) -> NUMBER
Descrição:
Retorna a soma de todos os valores numéricos, ignorando os não numéricos. Retorna
NaN se algum valor for NaN.
A saída terá o mesmo tipo de entrada maior, exceto nestes casos:
- Um
INTEGERserá convertido em umDOUBLEse não puder ser representado como umINTEGER.
Node.js
const result = await db.pipeline() .collection("cities") .aggregate(field("population").sum().as("totalPopulation")) .execute();
Web
const result = await execute(db.pipeline() .collection("cities") .aggregate(field("population").sum().as("totalPopulation")) );
Swift
let result = try await db.pipeline() .collection("cities") .aggregate([Field("population").sum().as("totalPopulation")]) .execute()
Kotlin
val result = db.pipeline() .collection("cities") .aggregate(AggregateFunction.sum("population").alias("totalPopulation")) .execute()
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("cities") .aggregate(AggregateFunction.sum("population").alias("totalPopulation")) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field result = ( client.pipeline() .collection("cities") .aggregate(Field.of("population").sum().as_("totalPopulation")) .execute() )
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("cities") .aggregate(sum("population").as("totalPopulation")) .execute() .get();
MÉDIA
Sintaxe:
average(expression: ANY) -> FLOAT64
Descrição:
Retorna a média de todos os valores numéricos, ignorando os não numéricos.
Será avaliado como NaN se algum valor for NaN ou NULL se nenhum valor numérico for agregado.
A saída terá o mesmo tipo da entrada, exceto nestes casos:
- Um
INTEGERserá convertido em umDOUBLEse não puder ser representado como umINTEGER.
Node.js
const result = await db.pipeline() .collection("cities") .aggregate(field("population").average().as("averagePopulation")) .execute();
Web
const result = await execute(db.pipeline() .collection("cities") .aggregate(field("population").average().as("averagePopulation")) );
Swift
let result = try await db.pipeline() .collection("cities") .aggregate([Field("population").average().as("averagePopulation")]) .execute()
Kotlin
val result = db.pipeline() .collection("cities") .aggregate(AggregateFunction.average("population").alias("averagePopulation")) .execute()
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("cities") .aggregate(AggregateFunction.average("population").alias("averagePopulation")) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field result = ( client.pipeline() .collection("cities") .aggregate(Field.of("population").average().as_("averagePopulation")) .execute() )
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("cities") .aggregate(average("population").as("averagePopulation")) .execute() .get();
MINIMUM
Sintaxe:
minimum(expression: ANY) -> ANY
Descrição:
Retorna o valor mínimo não NULL e não ausente de expression quando avaliado em cada documento.
Se não houver valores diferentes de NULL e ausentes, NULL será retornado. Isso inclui quando nenhum documento é considerado.
Se houver vários valores equivalentes mínimos, qualquer um deles poderá ser retornado. A ordem de tipo de valor segue a ordem documentada.
Node.js
const result = await db.pipeline() .collection("books") .aggregate(field("price").minimum().as("minimumPrice")) .execute();
Web
const result = await execute(db.pipeline() .collection("books") .aggregate(field("price").minimum().as("minimumPrice")) );
Swift
let result = try await db.pipeline() .collection("books") .aggregate([Field("price").minimum().as("minimumPrice")]) .execute()
Kotlin
val result = db.pipeline() .collection("books") .aggregate(AggregateFunction.minimum("price").alias("minimumPrice")) .execute()
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("books") .aggregate(AggregateFunction.minimum("price").alias("minimumPrice")) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field result = ( client.pipeline() .collection("books") .aggregate(Field.of("price").minimum().as_("minimumPrice")) .execute() )
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("books") .aggregate(minimum("price").as("minimumPrice")) .execute() .get();
MAXIMUM
Sintaxe:
maximum(expression: ANY) -> ANY
Descrição:
Retorna o valor máximo não NULL e não ausente de expression quando avaliado em cada documento.
Se não houver valores diferentes de NULL e ausentes, NULL será retornado. Isso inclui quando nenhum documento é considerado.
Se houver vários valores equivalentes máximos, qualquer um deles poderá ser retornado. A ordem de tipo de valor segue a ordem documentada.
Node.js
const result = await db.pipeline() .collection("books") .aggregate(field("price").maximum().as("maximumPrice")) .execute();
Web
const result = await execute(db.pipeline() .collection("books") .aggregate(field("price").maximum().as("maximumPrice")) );
Swift
let result = try await db.pipeline() .collection("books") .aggregate([Field("price").maximum().as("maximumPrice")]) .execute()
Kotlin
val result = db.pipeline() .collection("books") .aggregate(AggregateFunction.maximum("price").alias("maximumPrice")) .execute()
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("books") .aggregate(AggregateFunction.maximum("price").alias("maximumPrice")) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field result = ( client.pipeline() .collection("books") .aggregate(Field.of("price").maximum().as_("maximumPrice")) .execute() )
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("books") .aggregate(maximum("price").as("maximumPrice")) .execute() .get();
FIRST
Sintaxe:
first(expression: ANY) -> ANY
Descrição:
Retorna o valor de expression do primeiro documento retornado.
LAST
Sintaxe:
last(expression: ANY) -> ANY
Descrição:
Retorna o valor de expression do último documento retornado.
ARRAY_AGG
Sintaxe:
array_agg(expression: ANY) -> ARRAY<ANY>
Descrição:
Retorna uma matriz que contém todos os valores de expression quando avaliados em cada documento.
Se a expressão resultar em um valor ausente, ela será convertida em NULL.
A ordem dos elementos na matriz de saída não é estável e não deve ser usada como referência.
ARRAY_AGG_DISTINCT
Sintaxe:
array_agg_distinct(expression: ANY) -> ARRAY<ANY>
Descrição:
Retorna uma matriz que contém todos os valores distintos de expression quando avaliados em cada documento.
Se a expressão resultar em um valor ausente, ela será convertida em NULL.
A ordem dos elementos na matriz de saída não é estável e não deve ser usada como referência.