---
title: "POST /v1/{+parent}:runAggregationQuery"
method: POST
path: "/v1/{+parent}:runAggregationQuery"
tags: ["projects"]
---

# POST /v1/{+parent}:runAggregationQuery

`POST /v1/{+parent}:runAggregationQuery`

Runs an aggregation query. Rather than producing Document results like Firestore.RunQuery, this API allows running an aggregation to produce a series of AggregationResult server-side. High-Level Example: ``` -- Return the number of documents in table given a filter. SELECT COUNT(*) FROM ( SELECT * FROM k where a = true ); ```

## Path parameters

- `parent` string, required

## Request body

- RunAggregationQueryRequest — The request for Firestore.RunAggregationQuery.
  - `explainOptions` ExplainOptions — Explain options for the query.
    - `analyze` boolean — Optional. Whether to execute this query. When false (the default), the query will be planned, returning only metrics from the planning stages. When true, the query will be planned and executed, returning the full query results along with both planning and execution stage metrics.
  - `structuredAggregationQuery` StructuredAggregationQuery — Firestore query for running an aggregation over a StructuredQuery.
    - `structuredQuery` StructuredQuery — A Firestore query. The query stages are executed in the following order: 1. from 2. where 3. select 4. order_by + start_at + end_at 5. offset 6. limit 7. find_nearest
      - `select` Projection — The projection of document's fields to return.
        - `fields` FieldReference[] — The fields to return. If empty, all fields are returned. To only return the name of the document, use `['__name__']`.
          - `fieldPath` string — A reference to a field in a document. Requires: * MUST be a dot-delimited (`.`) string of segments, where each segment conforms to document field name limitations.
      - `startAt` Cursor — A position in a query result set.
        - `values` Value[] — The values that represent a position, in the order they appear in the order by clause of a query. Can contain fewer values than specified in the order by clause.
          - `timestampValue` string, google-datetime — A timestamp value. Precise only to microseconds. When stored, any additional precision is rounded down.
          - `pipelineValue` Pipeline — A Firestore query represented as an ordered list of operations / stages.
            - `stages` Stage[] — Required. Ordered list of stages to evaluate.
              - …
          - `booleanValue` boolean — A boolean value.
          - `geoPointValue` LatLng — An object that represents a latitude/longitude pair. This is expressed as a pair of doubles to represent degrees latitude and degrees longitude. Unless specified otherwise, this object must conform to the WGS84 standard. Values must be within normalized ranges.
            - `latitude` number, double — The latitude in degrees. It must be in the range [-90.0, +90.0].
            - `longitude` number, double — The longitude in degrees. It must be in the range [-180.0, +180.0].
          - `functionValue` Function — Represents an unevaluated scalar expression. For example, the expression `like(user_name, "%alice%")` is represented as: ``` name: "like" args { field_reference: "user_name" } args { string_value: "%alice%" } ```
            - `name` string — Required. The name of the function to evaluate. **Requires:** * must be in snake case (lower case with underscore separator).
            - `args` Value[] — Optional. Ordered list of arguments the given function expects.
            - `options` object — Optional. Optional named arguments that certain functions may support.
          - `variableReferenceValue` string — Pointer to a variable defined elsewhere in a pipeline. Unlike `field_reference_value` which references a field within a document, this refers to a variable, defined in a separate namespace than the fields of a document.
          - `arrayValue` ArrayValue — An array value.
            - `values` Value[] — Values in the array.
          - `fieldReferenceValue` string — Value which references a field. This is considered relative (vs absolute) since it only refers to a field and not a field within a particular document. **Requires:** * Must follow field reference limitations. * Not allowed to be used when writing documents.
          - `bytesValue` string, byte — A bytes value. Must not exceed 1 MiB - 89 bytes. Only the first 1,500 bytes are considered by queries.
          - `stringValue` string — A string value. The string, represented as UTF-8, must not exceed 1 MiB - 89 bytes. Only the first 1,500 bytes of the UTF-8 representation are considered by queries.
          - `mapValue` MapValue — A map value.
            - `fields` object — The map's fields. The map keys represent field names. Field names matching the regular expression `__.*__` are reserved. Reserved field names are forbidden except in certain documented contexts. The map keys, represented as UTF-8, must not exceed 1,500 bytes and cannot be empty.
          - `integerValue` string, int64 — An integer value.
          - `doubleValue` number, double — A double value.
          - `nullValue` 'NULL_VALUE' — A null value.
          - `referenceValue` string — A reference to a document. For example: `projects/{project_id}/databases/{database_id}/documents/{document_path}`.
        - `before` boolean — If the position is just before or just after the given values, relative to the sort order defined by the query.
      - `from` CollectionSelector[] — The collections to query.
        - `allDescendants` boolean — When false, selects only collections that are immediate children of the `parent` specified in the containing `RunQueryRequest`. When true, selects all descendant collections.
        - `collectionId` string — The collection ID. When set, selects only collections with this ID.
      - `findNearest` FindNearest — Nearest Neighbors search config. The ordering provided by FindNearest supersedes the order_by stage. If multiple documents have the same vector distance, the returned document order is not guaranteed to be stable between queries.
        - `limit` integer — Required. The number of nearest neighbors to return. Must be a positive integer of no more than 1000.
        - `distanceThreshold` number, double — Optional. Option to specify a threshold for which no less similar documents will be returned. The behavior of the specified `distance_measure` will affect the meaning of the distance threshold. Since DOT_PRODUCT distances increase when the vectors are more similar, the comparison is inverted. * For EUCLIDEAN, COSINE: `WHERE distance <= distance_threshold` * For DOT_PRODUCT: `WHERE distance >= distance_threshold`
        - `vectorField` FieldReference — A reference to a field in a document, ex: `stats.operations`.
          - `fieldPath` string — A reference to a field in a document. Requires: * MUST be a dot-delimited (`.`) string of segments, where each segment conforms to document field name limitations.
        - `distanceMeasure` 'DISTANCE_MEASURE_UNSPECIFIED' | 'EUCLIDEAN' | 'COSINE' | 'DOT_PRODUCT' — Required. The distance measure to use, required.
        - `distanceResultField` string — Optional. Optional name of the field to output the result of the vector distance calculation. Must conform to document field name limitations.
        - `queryVector` Value — A message that can hold any of the supported value types.
          - `timestampValue` string, google-datetime — A timestamp value. Precise only to microseconds. When stored, any additional precision is rounded down.
          - `pipelineValue` Pipeline — A Firestore query represented as an ordered list of operations / stages.
            - `stages` Stage[] — Required. Ordered list of stages to evaluate.
              - …
          - `booleanValue` boolean — A boolean value.
          - `geoPointValue` LatLng — An object that represents a latitude/longitude pair. This is expressed as a pair of doubles to represent degrees latitude and degrees longitude. Unless specified otherwise, this object must conform to the WGS84 standard. Values must be within normalized ranges.
            - `latitude` number, double — The latitude in degrees. It must be in the range [-90.0, +90.0].
            - `longitude` number, double — The longitude in degrees. It must be in the range [-180.0, +180.0].
          - `functionValue` Function — Represents an unevaluated scalar expression. For example, the expression `like(user_name, "%alice%")` is represented as: ``` name: "like" args { field_reference: "user_name" } args { string_value: "%alice%" } ```
            - `name` string — Required. The name of the function to evaluate. **Requires:** * must be in snake case (lower case with underscore separator).
            - `args` Value[] — Optional. Ordered list of arguments the given function expects.
            - `options` object — Optional. Optional named arguments that certain functions may support.
          - `variableReferenceValue` string — Pointer to a variable defined elsewhere in a pipeline. Unlike `field_reference_value` which references a field within a document, this refers to a variable, defined in a separate namespace than the fields of a document.
          - `arrayValue` ArrayValue — An array value.
            - `values` Value[] — Values in the array.
          - `fieldReferenceValue` string — Value which references a field. This is considered relative (vs absolute) since it only refers to a field and not a field within a particular document. **Requires:** * Must follow field reference limitations. * Not allowed to be used when writing documents.
          - `bytesValue` string, byte — A bytes value. Must not exceed 1 MiB - 89 bytes. Only the first 1,500 bytes are considered by queries.
          - `stringValue` string — A string value. The string, represented as UTF-8, must not exceed 1 MiB - 89 bytes. Only the first 1,500 bytes of the UTF-8 representation are considered by queries.
          - `mapValue` MapValue — A map value.
            - `fields` object — The map's fields. The map keys represent field names. Field names matching the regular expression `__.*__` are reserved. Reserved field names are forbidden except in certain documented contexts. The map keys, represented as UTF-8, must not exceed 1,500 bytes and cannot be empty.
          - `integerValue` string, int64 — An integer value.
          - `doubleValue` number, double — A double value.
          - `nullValue` 'NULL_VALUE' — A null value.
          - `referenceValue` string — A reference to a document. For example: `projects/{project_id}/databases/{database_id}/documents/{document_path}`.
      - `offset` integer — The number of documents to skip before returning the first result. This applies after the constraints specified by the `WHERE`, `START AT`, & `END AT` but before the `LIMIT` clause. Requires: * The value must be greater than or equal to zero if specified.
      - `where` Filter — A filter.
        - `compositeFilter` CompositeFilter — A filter that merges multiple other filters using the given operator.
          - `op` 'OPERATOR_UNSPECIFIED' | 'AND' | 'OR' — The operator for combining multiple filters.
          - `filters` Filter[] — The list of filters to combine. Requires: * At least one filter is present.
        - `fieldFilter` FieldFilter — A filter on a specific field.
          - `field` FieldReference — A reference to a field in a document, ex: `stats.operations`.
            - `fieldPath` string — A reference to a field in a document. Requires: * MUST be a dot-delimited (`.`) string of segments, where each segment conforms to document field name limitations.
          - `op` 'OPERATOR_UNSPECIFIED' | 'LESS_THAN' | 'LESS_THAN_OR_EQUAL' | 'GREATER_THAN' | 'GREATER_THAN_OR_EQUAL' | 'EQUAL' | 'NOT_EQUAL' | 'ARRAY_CONTAINS' | 'IN' | 'ARRAY_CONTAINS_ANY' | 'NOT_IN' — The operator to filter by.
          - `value` Value — A message that can hold any of the supported value types.
            - `timestampValue` string, google-datetime — A timestamp value. Precise only to microseconds. When stored, any additional precision is rounded down.
            - `pipelineValue` Pipeline — A Firestore query represented as an ordered list of operations / stages.
              - …
            - `booleanValue` boolean — A boolean value.
            - `geoPointValue` LatLng — An object that represents a latitude/longitude pair. This is expressed as a pair of doubles to represent degrees latitude and degrees longitude. Unless specified otherwise, this object must conform to the WGS84 standard. Values must be within normalized ranges.
              - …
            - `functionValue` Function — Represents an unevaluated scalar expression. For example, the expression `like(user_name, "%alice%")` is represented as: ``` name: "like" args { field_reference: "user_name" } args { string_value: "%alice%" } ```
              - …
            - `variableReferenceValue` string — Pointer to a variable defined elsewhere in a pipeline. Unlike `field_reference_value` which references a field within a document, this refers to a variable, defined in a separate namespace than the fields of a document.
            - `arrayValue` ArrayValue — An array value.
              - …
            - `fieldReferenceValue` string — Value which references a field. This is considered relative (vs absolute) since it only refers to a field and not a field within a particular document. **Requires:** * Must follow field reference limitations. * Not allowed to be used when writing documents.
            - `bytesValue` string, byte — A bytes value. Must not exceed 1 MiB - 89 bytes. Only the first 1,500 bytes are considered by queries.
            - `stringValue` string — A string value. The string, represented as UTF-8, must not exceed 1 MiB - 89 bytes. Only the first 1,500 bytes of the UTF-8 representation are considered by queries.
            - `mapValue` MapValue — A map value.
              - …
            - `integerValue` string, int64 — An integer value.
            - `doubleValue` number, double — A double value.
            - `nullValue` 'NULL_VALUE' — A null value.
            - `referenceValue` string — A reference to a document. For example: `projects/{project_id}/databases/{database_id}/documents/{document_path}`.
        - `unaryFilter` UnaryFilter — A filter with a single operand.
          - `op` 'OPERATOR_UNSPECIFIED' | 'IS_NAN' | 'IS_NULL' | 'IS_NOT_NAN' | 'IS_NOT_NULL' — The unary operator to apply.
          - `field` FieldReference — A reference to a field in a document, ex: `stats.operations`.
            - `fieldPath` string — A reference to a field in a document. Requires: * MUST be a dot-delimited (`.`) string of segments, where each segment conforms to document field name limitations.
      - `limit` integer — The maximum number of results to return. Applies after all other constraints. Requires: * The value must be greater than or equal to zero if specified.
      - `orderBy` Order[] — The order to apply to the query results. Callers can provide a full ordering, a partial ordering, or no ordering at all. While Firestore will always respect the provided order, the behavior for queries without a full ordering is different per database edition: In Standard edition, Firestore guarantees a stable ordering through the following rules: * The `order_by` is required to reference all fields used with an inequality filter. * All fields that are required to be in the `order_by` but are not already present are appended in lexicographical ordering of the field name. * If an order on `__name__` is not specified, it is appended by default. Fields are appended with the same sort direction as the last order specified, or 'ASCENDING' if no order was specified. For example: * `ORDER BY a` becomes `ORDER BY a ASC, __name__ ASC` * `ORDER BY a DESC` becomes `ORDER BY a DESC, __name__ DESC` * `WHERE a > 1` becomes `WHERE a > 1 ORDER BY a ASC, __name__ ASC` * `WHERE __name__ > ... AND a > 1` becomes `WHERE __name__ > ... AND a > 1 ORDER BY a ASC, __name__ ASC` In Enterprise edition, Firestore does not guarantee a stable ordering. Instead it will pick the most efficient ordering based on the indexes available at the time of query execution. This will result in a different ordering for queries that are otherwise identical. To ensure a stable ordering, always include a unique field in the `order_by` clause, such as `__name__`.
        - `field` FieldReference — A reference to a field in a document, ex: `stats.operations`.
          - `fieldPath` string — A reference to a field in a document. Requires: * MUST be a dot-delimited (`.`) string of segments, where each segment conforms to document field name limitations.
        - `direction` 'DIRECTION_UNSPECIFIED' | 'ASCENDING' | 'DESCENDING' — The direction to order by. Defaults to `ASCENDING`.
      - `endAt` Cursor — A position in a query result set.
        - `values` Value[] — The values that represent a position, in the order they appear in the order by clause of a query. Can contain fewer values than specified in the order by clause.
          - `timestampValue` string, google-datetime — A timestamp value. Precise only to microseconds. When stored, any additional precision is rounded down.
          - `pipelineValue` Pipeline — A Firestore query represented as an ordered list of operations / stages.
            - `stages` Stage[] — Required. Ordered list of stages to evaluate.
              - …
          - `booleanValue` boolean — A boolean value.
          - `geoPointValue` LatLng — An object that represents a latitude/longitude pair. This is expressed as a pair of doubles to represent degrees latitude and degrees longitude. Unless specified otherwise, this object must conform to the WGS84 standard. Values must be within normalized ranges.
            - `latitude` number, double — The latitude in degrees. It must be in the range [-90.0, +90.0].
            - `longitude` number, double — The longitude in degrees. It must be in the range [-180.0, +180.0].
          - `functionValue` Function — Represents an unevaluated scalar expression. For example, the expression `like(user_name, "%alice%")` is represented as: ``` name: "like" args { field_reference: "user_name" } args { string_value: "%alice%" } ```
            - `name` string — Required. The name of the function to evaluate. **Requires:** * must be in snake case (lower case with underscore separator).
            - `args` Value[] — Optional. Ordered list of arguments the given function expects.
            - `options` object — Optional. Optional named arguments that certain functions may support.
          - `variableReferenceValue` string — Pointer to a variable defined elsewhere in a pipeline. Unlike `field_reference_value` which references a field within a document, this refers to a variable, defined in a separate namespace than the fields of a document.
          - `arrayValue` ArrayValue — An array value.
            - `values` Value[] — Values in the array.
          - `fieldReferenceValue` string — Value which references a field. This is considered relative (vs absolute) since it only refers to a field and not a field within a particular document. **Requires:** * Must follow field reference limitations. * Not allowed to be used when writing documents.
          - `bytesValue` string, byte — A bytes value. Must not exceed 1 MiB - 89 bytes. Only the first 1,500 bytes are considered by queries.
          - `stringValue` string — A string value. The string, represented as UTF-8, must not exceed 1 MiB - 89 bytes. Only the first 1,500 bytes of the UTF-8 representation are considered by queries.
          - `mapValue` MapValue — A map value.
            - `fields` object — The map's fields. The map keys represent field names. Field names matching the regular expression `__.*__` are reserved. Reserved field names are forbidden except in certain documented contexts. The map keys, represented as UTF-8, must not exceed 1,500 bytes and cannot be empty.
          - `integerValue` string, int64 — An integer value.
          - `doubleValue` number, double — A double value.
          - `nullValue` 'NULL_VALUE' — A null value.
          - `referenceValue` string — A reference to a document. For example: `projects/{project_id}/databases/{database_id}/documents/{document_path}`.
        - `before` boolean — If the position is just before or just after the given values, relative to the sort order defined by the query.
    - `aggregations` Aggregation[] — Optional. Series of aggregations to apply over the results of the `structured_query`. Requires: * A minimum of one and maximum of five aggregations per query.
      - `count` Count — Count of documents that match the query. The `COUNT(*)` aggregation function operates on the entire document so it does not require a field reference.
        - `upTo` string, int64 — Optional. Optional constraint on the maximum number of documents to count. This provides a way to set an upper bound on the number of documents to scan, limiting latency, and cost. Unspecified is interpreted as no bound. High-Level Example: ``` AGGREGATE COUNT_UP_TO(1000) OVER ( SELECT * FROM k ); ``` Requires: * Must be greater than zero when present.
      - `sum` Sum — Sum of the values of the requested field. * Only numeric values will be aggregated. All non-numeric values including `NULL` are skipped. * If the aggregated values contain `NaN`, returns `NaN`. Infinity math follows IEEE-754 standards. * If the aggregated value set is empty, returns 0. * Returns a 64-bit integer if all aggregated numbers are integers and the sum result does not overflow. Otherwise, the result is returned as a double. Note that even if all the aggregated values are integers, the result is returned as a double if it cannot fit within a 64-bit signed integer. When this occurs, the returned value will lose precision. * When underflow occurs, floating-point aggregation is non-deterministic. This means that running the same query repeatedly without any changes to the underlying values could produce slightly different results each time. In those cases, values should be stored as integers over floating-point numbers.
        - `field` FieldReference — A reference to a field in a document, ex: `stats.operations`.
          - `fieldPath` string — A reference to a field in a document. Requires: * MUST be a dot-delimited (`.`) string of segments, where each segment conforms to document field name limitations.
      - `avg` Avg — Average of the values of the requested field. * Only numeric values will be aggregated. All non-numeric values including `NULL` are skipped. * If the aggregated values contain `NaN`, returns `NaN`. Infinity math follows IEEE-754 standards. * If the aggregated value set is empty, returns `NULL`. * Always returns the result as a double.
        - `field` FieldReference — A reference to a field in a document, ex: `stats.operations`.
          - `fieldPath` string — A reference to a field in a document. Requires: * MUST be a dot-delimited (`.`) string of segments, where each segment conforms to document field name limitations.
      - `alias` string — Optional. Optional name of the field to store the result of the aggregation into. If not provided, Firestore will pick a default name following the format `field_`. For example: ``` AGGREGATE COUNT_UP_TO(1) AS count_up_to_1, COUNT_UP_TO(2), COUNT_UP_TO(3) AS count_up_to_3, COUNT(*) OVER ( ... ); ``` becomes: ``` AGGREGATE COUNT_UP_TO(1) AS count_up_to_1, COUNT_UP_TO(2) AS field_1, COUNT_UP_TO(3) AS count_up_to_3, COUNT(*) AS field_2 OVER ( ... ); ``` Requires: * Must be unique across all aggregation aliases. * Conform to document field name limitations.
  - `requestOptions` RequestOptions — Options for a server request.
    - `requestTags` string[] — Optional. The request tags for the request.
  - `transaction` string, byte — Run the aggregation within an already active transaction. The value here is the opaque transaction ID to execute the query in.
  - `newTransaction` TransactionOptions — Options for creating a new transaction.
    - `readOnly` ReadOnly — Options for a transaction that can only be used to read documents.
      - `readTime` string, google-datetime — Reads documents at the given time. This must be a microsecond precision timestamp within the past one hour, or if Point-in-Time Recovery is enabled, can additionally be a whole minute timestamp within the past 7 days.
    - `readWrite` ReadWrite — Options for a transaction that can be used to read and write documents.
      - `concurrencyMode` 'CONCURRENCY_MODE_UNSPECIFIED' | 'OPTIMISTIC' | 'PESSIMISTIC' — Optional. The concurrency control mode to use for this transaction. A database is able to use different concurrency modes for different transactions simultaneously. 3rd party auth requests are only allowed to create optimistic read-write transactions and must specify that here even if the database-level setting is already configured to optimistic.
      - `retryTransaction` string, byte — An optional transaction to retry.
  - `readTime` string, google-datetime — Executes the query at the given timestamp. This must be a microsecond precision timestamp within the past one hour, or if Point-in-Time Recovery is enabled, can additionally be a whole minute timestamp within the past 7 days.

## Response `200`

Successful response

---

[API](https://skmtc.net/google/apis/firestore.md) · [All operations](https://skmtc.net/google/apis/firestore/llms.txt) · [OpenAPI document](https://skmtc-service-staging.skmtc.workers.dev/v1/apis/google/firestore/revisions/11bc07a83431/schema)
