> Documentation index: https://firebase.google.com/docs/reference/js/llms.txt

**Signature:**

```typescript
export declare class Pipeline 
```

## Methods

| Method | Modifiers | Description |
|---|---|---|
| [addFields(field, additionalFields)](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipelineaddfields) |   | Adds new fields to outputs from previous stages.This stage allows you to compute values on-the-fly based on existing data from previous stages or constants. You can use this to create new fields or overwrite existing ones (if there is name overlaps).The added fields are defined using [Selectable](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.selectable.md.txt#selectable_interface)s, which can be: - [Field](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.field.md.txt#field_class): References an existing document field. - [Expression](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.expression.md.txt#expression_class): Either a literal value (see [constant()](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.md.txt#constant_27f5011)) or a computed value with an assigned alias using [Expression.as()](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.expression.md.txt#expressionas). |
| [addFields(options)](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipelineaddfields) |   | Adds new fields to outputs from previous stages.This stage allows you to compute values on-the-fly based on existing data from previous stages or constants. You can use this to create new fields or overwrite existing ones (if there is name overlaps).The added fields are defined using [Selectable](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.selectable.md.txt#selectable_interface)s, which can be: - [Field](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.field.md.txt#field_class): References an existing document field. - [Expression](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.expression.md.txt#expression_class): Either a literal value (see [constant()](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.md.txt#constant_27f5011)) or a computed value with an assigned alias using [Expression.as()](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.expression.md.txt#expressionas). |
| [addWindowFields(window, field, additionalFields)](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipelineaddwindowfields) |   | ***(Public Preview)*** Adds window function results to the output documents of the pipeline.Window Functions SDK features are in preview until the backend feature launches. Look for launch announcement at: https://docs.cloud.google.com/firestore/docs/release-notesWindow functions evaluate expressions over a subset of documents (a "window frame") relative to the current document: - In a `documents` frame, bounds are positional document counts relative to the current document's position (`'current'` refers strictly to the current document's position; ties are not included). For `preceding`, a positive integer (e.g. `2`) includes up to that many documents before the current document, and a negative integer (e.g. `-1`) indicates a boundary following the current document, enabling frames that start after the current document. For `following`, a positive integer (e.g. `2`) includes up to that many documents after the current document, and a negative integer (e.g. `-1`) indicates a boundary preceding the current document, enabling frames that end before the current document (e.g. excluding the current document). Specifying `sort` is optional. - In a `range` frame, bounds are value or time offsets relative to the current document's sort value(s) (`'current'` is peer-inclusive and includes all documents tied with the current document's sort value(s), equivalent to an offset of `0`). For `preceding`, a positive offset subtracts from the current document's sort value (looking into the past), and a negative offset adds to the current document's sort value (shifting the lower boundary past the current document). For `following`, a positive offset adds to the current document's sort value (looking into the future), and a negative offset subtracts from the current document's sort value (shifting the upper boundary before the current document). One or more `sort` expressions are required: range frames with numeric or time-unit offsets require a single numeric or timestamp `sort` expression, whereas range frames bounded only by `'current'` and `'unbounded'` support multiple `sort` expressions and non-numeric sort values (such as strings or booleans). - When neither `documents` nor `range` is specified, an unsorted window defaults to `documents` from `'unbounded'` preceding to `'unbounded'` following, and a sorted window defaults to `range` from `'unbounded'` preceding to `'current'` following (peer-inclusive). |
| [addWindowFields(options)](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipelineaddwindowfields) |   | ***(Public Preview)*** Adds window function results to the output documents of the pipeline using options.Window Functions SDK features are in preview until the backend feature launches. Look for launch announcement at: https://docs.cloud.google.com/firestore/docs/release-notes |
| [aggregate(accumulator, additionalAccumulators)](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipelineaggregate) |   | Performs aggregation operations on the documents from previous stages.This stage allows you to calculate aggregate values over a set of documents. You define the aggregations to perform using [AliasedAggregate](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.aliasedaggregate.md.txt#aliasedaggregate_class) expressions which are typically results of calling [Expression.as()](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.expression.md.txt#expressionas) on [AggregateFunction](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.aggregatefunction.md.txt#aggregatefunction_class) instances. |
| [aggregate(options)](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipelineaggregate) |   | Performs optionally grouped aggregation operations on the documents from previous stages.This stage allows you to calculate aggregate values over a set of documents, optionally grouped by one or more fields or functions. You can specify: - Grouping Fields or Functions: One or more fields or functions to group the documents by. For each distinct combination of values in these fields, a separate group is created. If no grouping fields are provided, a single group containing all documents is used. Not specifying groups is the same as putting the entire inputs into one group. - Accumulators: One or more accumulation operations to perform within each group. These are defined using [AliasedAggregate](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.aliasedaggregate.md.txt#aliasedaggregate_class) expressions, which are typically created by calling [Expression.as()](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.expression.md.txt#expressionas) on [AggregateFunction](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.aggregatefunction.md.txt#aggregatefunction_class) instances. Each aggregation calculates a value (e.g., sum, average, count) based on the documents within its group. |
| [define(aliasedExpression, additionalExpressions)](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipelinedefine) |   | Defines one or more variables in the pipeline's scope. `define` is used to bind a value to a variable for internal reuse within the pipeline body (accessed via the `variable()` function).This stage is useful for declaring reusable values or intermediate calculations that can be referenced multiple times in later parts of the pipeline, improving readability and maintainability.Each variable is defined using an [AliasedExpression](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.aliasedexpression.md.txt#aliasedexpression_class), which pairs an expression with a name (alias). The expression can be a simple constant, a field reference, or a complex computation. |
| [define(options)](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipelinedefine) |   | Defines one or more variables in the pipeline's scope. `define` is used to bind a value to a variable for internal reuse within the pipeline body (accessed via the `variable()` function).This stage is useful for declaring reusable values or intermediate calculations that can be referenced multiple times in later parts of the pipeline, improving readability and maintainability.Each variable is defined using an [AliasedExpression](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.aliasedexpression.md.txt#aliasedexpression_class), which pairs an expression with a name (alias). The expression can be a simple constant, a field reference, or a complex computation. |
| [delete()](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipelinedelete) |   | Performs a delete operation on documents from previous stages. |
| [delete(options)](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipelinedelete) |   | Performs a delete operation on documents from previous stages with options. |
| [distinct(group, additionalGroups)](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipelinedistinct) |   | Returns a set of distinct values from the inputs to this stage.This stage runs through the results from previous stages to include only results with unique combinations of [Expression](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.expression.md.txt#expression_class) values ([Field](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.field.md.txt#field_class), [AliasedExpression](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.aliasedexpression.md.txt#aliasedexpression_class), etc).The parameters to this stage are defined using [Selectable](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.selectable.md.txt#selectable_interface) expressions or strings: - `string`: Name of an existing field - [Field](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.field.md.txt#field_class): References an existing document field. - [AliasedExpression](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.aliasedexpression.md.txt#aliasedexpression_class): Represents the result of a function with an assigned alias name using [Expression.as()](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.expression.md.txt#expressionas). |
| [distinct(options)](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipelinedistinct) |   | Returns a set of distinct values from the inputs to this stage.This stage runs through the results from previous stages to include only results with unique combinations of [Expression](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.expression.md.txt#expression_class) values ([Field](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.field.md.txt#field_class), [AliasedExpression](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.aliasedexpression.md.txt#aliasedexpression_class), etc).The parameters to this stage are defined using [Selectable](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.selectable.md.txt#selectable_interface) expressions or strings: - `string`: Name of an existing field - [Field](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.field.md.txt#field_class): References an existing document field. - [AliasedExpression](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.aliasedexpression.md.txt#aliasedexpression_class): Represents the result of a function with an assigned alias name using [Expression.as()](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.expression.md.txt#expressionas). |
| [findNearest(options)](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipelinefindnearest) |   | Performs a vector proximity search on the documents from the previous stage, returning the K-nearest documents based on the specified query `vectorValue` and `distanceMeasure`. The returned documents will be sorted in order from nearest to furthest from the query `vectorValue`. |
| [insert()](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipelineinsert) |   | Performs an insert operation using documents from previous stages.Each input document is inserted at the path in its `name` field. The operation fails if a target document already exists. See [InsertStageOptions](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.md.txt#insertstageoptions) for details. |
| [insert(options)](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipelineinsert) |   | Performs an insert operation with options.The operation fails if a target document already exists. See [InsertStageOptions](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.md.txt#insertstageoptions) for how the target path is determined. |
| [limit(limit)](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipelinelimit) |   | Limits the maximum number of documents returned by previous stages to `limit`. This stage is particularly useful when you want to retrieve a controlled subset of data from a potentially large result set. It's often used for: - Pagination: In combination with [Pipeline.offset](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.pipeline.md.txt#pipelineoffset) to retrieve specific pages of results. - Limiting Data Retrieval: To prevent excessive data transfer and improve performance, especially when dealing with large collections. |
| [limit(options)](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipelinelimit) |   | Limits the maximum number of documents returned by previous stages to `limit`. This stage is particularly useful when you want to retrieve a controlled subset of data from a potentially large result set. It's often used for: - Pagination: In combination with [Pipeline.offset](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.pipeline.md.txt#pipelineoffset) to retrieve specific pages of results. - Limiting Data Retrieval: To prevent excessive data transfer and improve performance, especially when dealing with large collections. |
| [offset(offset)](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipelineoffset) |   | Skips the first `offset` number of documents from the results of previous stages. This stage is useful for implementing pagination in your pipelines, allowing you to retrieve results in chunks. It is typically used in conjunction with [Pipeline.limit](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.pipeline.md.txt#pipelinelimit) to control the size of each page. |
| [offset(options)](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipelineoffset) |   | Skips the first `offset` number of documents from the results of previous stages. This stage is useful for implementing pagination in your pipelines, allowing you to retrieve results in chunks. It is typically used in conjunction with [Pipeline.limit](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.pipeline.md.txt#pipelinelimit) to control the size of each page. |
| [rawStage(name, params, options)](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipelinerawstage) |   | Adds a raw stage to the pipeline. This method provides a flexible way to extend the pipeline's functionality by adding custom stages. Each raw stage is defined by a unique `name` and a set of `params` that control its behavior. Example (Assuming there is no 'where' stage available in SDK): |
| [removeFields(fieldValue, additionalFields)](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipelineremovefields) |   | Remove fields from outputs of previous stages. |
| [removeFields(options)](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipelineremovefields) |   | Remove fields from outputs of previous stages. |
| [replaceWith(fieldName)](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipelinereplacewith) |   | Fully overwrites all fields in a document with those coming from a nested map. This stage allows you to emit a map value as a document. Each key of the map becomes a field on the document that contains the corresponding value. |
| [replaceWith(expr)](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipelinereplacewith) |   | Fully overwrites all fields in a document with those coming from a map. This stage allows you to emit a map value as a document. Each key of the map becomes a field on the document that contains the corresponding value. |
| [replaceWith(options)](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipelinereplacewith) |   | Fully overwrites all fields in a document with those coming from a map. This stage allows you to emit a map value as a document. Each key of the map becomes a field on the document that contains the corresponding value. |
| [sample(documents)](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipelinesample) |   | Performs a pseudo-random sampling of the documents from the previous stage. This stage will filter documents pseudo-randomly. The parameter specifies how number of documents to be returned. Examples: |
| [sample(options)](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipelinesample) |   | Performs a pseudo-random sampling of the documents from the previous stage. This stage will filter documents pseudo-randomly. The 'options' parameter specifies how sampling will be performed. See [SampleStageOptions](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.md.txt#samplestageoptions) for more information. |
| [search(options)](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipelinesearch) |   | Add a search stage to the Pipeline. The search stage supports full-text search and geo search expressions. |
| [select(selection, additionalSelections)](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipelineselect) |   | Selects or creates a set of fields from the outputs of previous stages. The selected fields are defined using [Selectable](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.selectable.md.txt#selectable_interface) expressions, which can be: - `string` : Name of an existing field - [Field](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.field.md.txt#field_class): References an existing field. - [AliasedExpression](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.aliasedexpression.md.txt#aliasedexpression_class): Represents the result of a function with an assigned alias name using [Expression.as()](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.expression.md.txt#expressionas) If no selections are provided, the output of this stage is empty. Use [Pipeline.addFields()](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.pipeline.md.txt#pipelineaddfields) instead if only additions are desired. |
| [select(options)](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipelineselect) |   | Selects or creates a set of fields from the outputs of previous stages. The selected fields are defined using [Selectable](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.selectable.md.txt#selectable_interface) expressions, which can be: - `string`: Name of an existing field - [Field](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.field.md.txt#field_class): References an existing field. - [AliasedExpression](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.aliasedexpression.md.txt#aliasedexpression_class): Represents the result of a function with an assigned alias name using [Expression.as()](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.expression.md.txt#expressionas) If no selections are provided, the output of this stage is empty. Use [Pipeline.addFields()](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.pipeline.md.txt#pipelineaddfields) instead if only additions are desired. |
| [sort(ordering, additionalOrderings)](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipelinesort) |   | Sorts the documents from previous stages based on one or more [Ordering](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.ordering.md.txt#ordering_class) criteria. This stage allows you to order the results of your pipeline. You can specify multiple [Ordering](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.ordering.md.txt#ordering_class) instances to sort by multiple fields in ascending or descending order. If documents have the same value for a field used for sorting, the next specified ordering will be used. If all orderings result in equal comparison, the documents are considered equal and the order is unspecified. |
| [sort(options)](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipelinesort) |   | Sorts the documents from previous stages based on one or more [Ordering](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.ordering.md.txt#ordering_class) criteria. This stage allows you to order the results of your pipeline. You can specify multiple [Ordering](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.ordering.md.txt#ordering_class) instances to sort by multiple fields in ascending or descending order. If documents have the same value for a field used for sorting, the next specified ordering will be used. If all orderings result in equal comparison, the documents are considered equal and the order is unspecified. |
| [toArrayExpression()](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipelinetoarrayexpression) |   | Converts this Pipeline into an expression that evaluates to an array of results. Result Unwrapping: - If the items have a single field, their values are unwrapped and returned directly in the array. - If the items have multiple fields, they are returned as objects in the array |
| [toScalarExpression()](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipelinetoscalarexpression) |   | Converts this Pipeline into an expression that evaluates to a single scalar result. **Runtime Validation:** The runtime validates that the result set contains zero or one item. If zero items, it evaluates to `null`. Result Unwrapping: - If the item has a single field, its value is unwrapped and returned directly. - If the item has multiple fields, they are returned as an object. |
| [union(other)](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipelineunion) |   | Performs union of all documents from two pipelines, including duplicates. This stage will pass through documents from previous stage, and also pass through documents from previous stage of the `other` [Pipeline](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.pipeline.md.txt#pipeline_class) given in parameter. The order of documents emitted from this stage is undefined. |
| [union(options)](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipelineunion) |   | Performs union of all documents from two pipelines, including duplicates. This stage will pass through documents from previous stage, and also pass through documents from previous stage of the `other` [Pipeline](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.pipeline.md.txt#pipeline_class) given in parameter. The order of documents emitted from this stage is undefined. |
| [unnest(selectable, indexField)](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipelineunnest) |   | Produces a document for each element in an input array.For each previous stage document, this stage will emit zero or more augmented documents. The input array specified by the `selectable` parameter, will emit an augmented document for each input array element. The input array element will augment the previous stage document by setting the `alias` field with the array element value.When `selectable` evaluates to a non-array value (ex: number, null, absent), then the stage becomes a no-op for the current input document, returning it as is with the `alias` field absent.No documents are emitted when `selectable` evaluates to an empty array. |
| [unnest(options)](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipelineunnest) |   | Produces a document for each element in an input array.For each previous stage document, this stage will emit zero or more augmented documents. The input array specified by the `selectable` parameter, will emit an augmented document for each input array element. The input array element will augment the previous stage document by setting the `alias` field with the array element value.When `selectable` evaluates to a non-array value (ex: number, null, absent), then the stage becomes a no-op for the current input document, returning it as is with the `alias` field absent.No documents are emitted when `selectable` evaluates to an empty array. |
| [update()](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipelineupdate) |   | Performs an update operation using documents from previous stages.Each input document is written to the path in its `name` field. See [UpdateStageOptions](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.md.txt#updatestageoptions) for details. |
| [update(transformedField, additionalFields)](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipelineupdate) |   | Performs an update operation using documents from previous stages.Each input document is written to the path in its `name` field. See [UpdateStageOptions](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.md.txt#updatestageoptions) for details. |
| [update(options)](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipelineupdate) |   | Performs an update operation with options. |
| [upsert()](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipelineupsert) |   | Performs an upsert operation using documents from previous stages.Each input document is written to the path in its `name` field. See [UpsertStageOptions](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.md.txt#upsertstageoptions) for details. |
| [upsert(additionalField, additionalFields)](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipelineupsert) |   | Performs an upsert operation using documents from previous stages.Each input document is written to the path in its `name` field. See [UpsertStageOptions](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.md.txt#upsertstageoptions) for details. |
| [upsert(options)](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipelineupsert) |   | Performs an upsert operation with options.See [UpsertStageOptions](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.md.txt#upsertstageoptions) for how the target path is determined. |
| [where(condition)](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipelinewhere) |   | Filters the documents from previous stages to only include those matching the specified [BooleanExpression](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.booleanexpression.md.txt#booleanexpression_class). This stage allows you to apply conditions to the data, similar to a "WHERE" clause in SQL. You can filter documents based on their field values, using implementations of [BooleanExpression](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.booleanexpression.md.txt#booleanexpression_class), typically including but not limited to: - field comparators: [Expression.equal()](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.expression.md.txt#expressionequal), [Expression.lessThan()](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.expression.md.txt#expressionlessthan), [Expression.greaterThan()](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.expression.md.txt#expressiongreaterthan), etc. - logical operators: [and](https://firebase.google.com/docs/reference/js/firestore.md.txt#and_e72c712), [or](https://firebase.google.com/docs/reference/js/firestore.md.txt#or_e72c712), [not](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.md.txt#not_c5b8fb1), etc. - advanced functions: [Expression.regexMatch()](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.expression.md.txt#expressionregexmatch), [Expression.arrayContains()](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.expression.md.txt#expressionarraycontains), etc. |
| [where(options)](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipelinewhere) |   | Filters the documents from previous stages to only include those matching the specified [BooleanExpression](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.booleanexpression.md.txt#booleanexpression_class). This stage allows you to apply conditions to the data, similar to a "WHERE" clause in SQL. You can filter documents based on their field values, using implementations of [BooleanExpression](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.booleanexpression.md.txt#booleanexpression_class), typically including but not limited to: - field comparators: [Expression.equal()](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.expression.md.txt#expressionequal), [Expression.lessThan()](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.expression.md.txt#expressionlessthan) (less than), [Expression.greaterThan()](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.expression.md.txt#expressiongreaterthan), etc. - logical operators: [and](https://firebase.google.com/docs/reference/js/firestore.md.txt#and_e72c712), [or](https://firebase.google.com/docs/reference/js/firestore.md.txt#or_e72c712), [not](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.md.txt#not_c5b8fb1), etc. - advanced functions: [Expression.regexMatch()](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.expression.md.txt#expressionregexmatch), [Expression.arrayContains()](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.expression.md.txt#expressionarraycontains), etc. |

## Pipeline.addFields()

Adds new fields to outputs from previous stages.

This stage allows you to compute values on-the-fly based on existing data from previous stages or constants. You can use this to create new fields or overwrite existing ones (if there is name overlaps).

The added fields are defined using [Selectable](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.selectable.md.txt#selectable_interface)s, which can be:

- \[Field\](./firestore_lite_pipelines.field#field_class): References an existing document field.
- \[Expression\](./firestore_lite_pipelines.expression#expression_class): Either a literal value (see \[constant()\](./firestore_lite_pipelines#constant_27f5011)) or a computed value with an assigned alias using \[Expression.as()\](./firestore_lite_pipelines.expression#expressionas).

**Signature:**

```typescript
addFields(field: Selectable, ...additionalFields: Selectable[]): Pipeline;
```

#### Parameters

| Parameter | Type | Description |
|---|---|---|
| field | [Selectable](https://firebase.google.com/docs/reference/js/firestore_pipelines.selectable.md.txt#selectable_interface) | The first field to add to the documents, specified as a [Selectable](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.selectable.md.txt#selectable_interface). |
| additionalFields | [Selectable](https://firebase.google.com/docs/reference/js/firestore_pipelines.selectable.md.txt#selectable_interface)\[\] | Optional additional fields to add to the documents, specified as [Selectable](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.selectable.md.txt#selectable_interface)s. |

**Returns:**

[Pipeline](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipeline_class)

A new Pipeline object with this stage appended to the stage list.

### Example

```typescript
firestore.pipeline().collection("books")
  .addFields(
    field("rating").as("bookRating"), // Rename 'rating' to 'bookRating'
    add(field("quantity"), 5).as("totalCost")  // Calculate 'totalCost'
  );

```

## Pipeline.addFields()

Adds new fields to outputs from previous stages.

This stage allows you to compute values on-the-fly based on existing data from previous stages or constants. You can use this to create new fields or overwrite existing ones (if there is name overlaps).

The added fields are defined using [Selectable](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.selectable.md.txt#selectable_interface)s, which can be:

- \[Field\](./firestore_lite_pipelines.field#field_class): References an existing document field.
- \[Expression\](./firestore_lite_pipelines.expression#expression_class): Either a literal value (see \[constant()\](./firestore_lite_pipelines#constant_27f5011)) or a computed value with an assigned alias using \[Expression.as()\](./firestore_lite_pipelines.expression#expressionas).

**Signature:**

```typescript
addFields(options: AddFieldsStageOptions): Pipeline;
```

#### Parameters

| Parameter | Type | Description |
|---|---|---|
| options | [AddFieldsStageOptions](https://firebase.google.com/docs/reference/js/firestore_pipelines.md.txt#addfieldsstageoptions) | An object that specifies required and optional parameters for the stage. |

**Returns:**

[Pipeline](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipeline_class)

A new Pipeline object with this stage appended to the stage list.

### Example

```typescript
firestore.pipeline().collection("books")
  .addFields(
    field("rating").as("bookRating"), // Rename 'rating' to 'bookRating'
    add(field("quantity"), 5).as("totalCost")  // Calculate 'totalCost'
  );

```

## Pipeline.addWindowFields()

> This API is provided as a preview for developers and may change based on feedback that we receive. Do not use this API in a production environment.

Adds window function results to the output documents of the pipeline.

Window Functions SDK features are in preview until the backend feature launches. Look for launch announcement at: https://docs.cloud.google.com/firestore/docs/release-notes

Window functions evaluate expressions over a subset of documents (a "window frame") relative to the current document: - In a `documents` frame, bounds are positional document counts relative to the current document's position (`'current'` refers strictly to the current document's position; ties are not included). For `preceding`, a positive integer (e.g. `2`) includes up to that many documents before the current document, and a negative integer (e.g. `-1`) indicates a boundary following the current document, enabling frames that start after the current document. For `following`, a positive integer (e.g. `2`) includes up to that many documents after the current document, and a negative integer (e.g. `-1`) indicates a boundary preceding the current document, enabling frames that end before the current document (e.g. excluding the current document). Specifying `sort` is optional. - In a `range` frame, bounds are value or time offsets relative to the current document's sort value(s) (`'current'` is peer-inclusive and includes all documents tied with the current document's sort value(s), equivalent to an offset of `0`). For `preceding`, a positive offset subtracts from the current document's sort value (looking into the past), and a negative offset adds to the current document's sort value (shifting the lower boundary past the current document). For `following`, a positive offset adds to the current document's sort value (looking into the future), and a negative offset subtracts from the current document's sort value (shifting the upper boundary before the current document). One or more `sort` expressions are required: range frames with numeric or time-unit offsets require a single numeric or timestamp `sort` expression, whereas range frames bounded only by `'current'` and `'unbounded'` support multiple `sort` expressions and non-numeric sort values (such as strings or booleans). - When neither `documents` nor `range` is specified, an unsorted window defaults to `documents` from `'unbounded'` preceding to `'unbounded'` following, and a sorted window defaults to `range` from `'unbounded'` preceding to `'current'` following (peer-inclusive).

**Signature:**

```typescript
addWindowFields(
    window: WindowSpec,
    field: AliasedAggregate | AliasedWindowFunction,
    ...additionalFields: Array<AliasedAggregate | AliasedWindowFunction>
  ): Pipeline;
```

#### Parameters

| Parameter | Type | Description |
|---|---|---|
| window | [WindowSpec](https://firebase.google.com/docs/reference/js/firestore_pipelines.md.txt#windowspec) | The specification defining how documents are partitioned, ordered, and bounded in the window frame. |
| field | [AliasedAggregate](https://firebase.google.com/docs/reference/js/firestore_pipelines.aliasedaggregate.md.txt#aliasedaggregate_class) \| [AliasedWindowFunction](https://firebase.google.com/docs/reference/js/firestore_pipelines.aliasedwindowfunction.md.txt#aliasedwindowfunction_class) | The first window field to add, specified as an [AliasedAggregate](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.aliasedaggregate.md.txt#aliasedaggregate_class). |
| additionalFields | Array\<[AliasedAggregate](https://firebase.google.com/docs/reference/js/firestore_pipelines.aliasedaggregate.md.txt#aliasedaggregate_class) \| [AliasedWindowFunction](https://firebase.google.com/docs/reference/js/firestore_pipelines.aliasedwindowfunction.md.txt#aliasedwindowfunction_class)\> | Optional additional window fields to add to the documents. |

**Returns:**

[Pipeline](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipeline_class)

A new Pipeline object with this stage appended to the stage list.

### Example

```typescript
// 1. Unsorted partition/group aggregation (evaluates over the entire group)
firestore.pipeline().collection("employees")
  .addWindowFields(
    {
      partition: ['department']
    },
    average(field('salary')).as('departmentAverageSalary')
  );

// 2. Document-based moving average with explicit boundaries
firestore.pipeline().collection("sales")
  .addWindowFields(
    {
      sort: ascending('date'),
      documents: { preceding: 1, following: 1 }
    },
    average(field('amount')).as('movingAverageAmount')
  );

// 3. Document-based running total (unbounded preceding to current document's position; ties are not included).
// Note: Offsets are physical document counts, so no time unit is required or used even when sorting on 'date'.
firestore.pipeline().collection("sales")
  .addWindowFields(
    {
      sort: ascending('date'),
      documents: { preceding: 'unbounded', following: 'current' }
    },
    sum(field('amount')).as('runningTotal')
  );

// 4. Range-based running average (unbounded preceding to current sort value, including all tied peers)
firestore.pipeline().collection("products")
  .addWindowFields(
    {
      sort: ascending('price'),
      range: { preceding: 'unbounded', following: 'current' }
    },
    average(field('rating')).as('cumulativeAvgRating')
  );

// 5. Range-based date/time window with a time unit (cumulative sales over the last 30 days)
firestore.pipeline().collection("sales")
  .addWindowFields(
    {
      sort: ascending('date'),
      range: { preceding: 30, following: 'current', unit: 'day' }
    },
    sum(field('amount')).as('thirtyDayCumulativeSales')
  );

```

## Pipeline.addWindowFields()

> This API is provided as a preview for developers and may change based on feedback that we receive. Do not use this API in a production environment.

Adds window function results to the output documents of the pipeline using options.

Window Functions SDK features are in preview until the backend feature launches. Look for launch announcement at: https://docs.cloud.google.com/firestore/docs/release-notes

**Signature:**

```typescript
addWindowFields(options: AddWindowFieldsStageOptions): Pipeline;
```

#### Parameters

| Parameter | Type | Description |
|---|---|---|
| options | [AddWindowFieldsStageOptions](https://firebase.google.com/docs/reference/js/firestore_pipelines.md.txt#addwindowfieldsstageoptions) | An object specifying the window frame configuration and the fields to add. |

**Returns:**

[Pipeline](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipeline_class)

A new Pipeline object with this stage appended to the stage list.

### Example

```typescript
// 1. Unsorted partition/group aggregation using options
firestore.pipeline().collection("employees")
  .addWindowFields({
    window: {
      partition: ['department']
    },
    fields: [
      average(field('salary')).as('departmentAverageSalary')
    ]
  });

// 2. Document-based moving average using options
firestore.pipeline().collection("sales")
  .addWindowFields({
    window: {
      sort: ascending('date'),
      documents: { preceding: 1, following: 1 }
    },
    fields: [
      average(field('amount')).as('movingAverageAmount')
    ]
  });

```

## Pipeline.aggregate()

Performs aggregation operations on the documents from previous stages.

This stage allows you to calculate aggregate values over a set of documents. You define the aggregations to perform using [AliasedAggregate](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.aliasedaggregate.md.txt#aliasedaggregate_class) expressions which are typically results of calling [Expression.as()](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.expression.md.txt#expressionas) on [AggregateFunction](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.aggregatefunction.md.txt#aggregatefunction_class) instances.

**Signature:**

```typescript
aggregate(
    accumulator: AliasedAggregate,
    ...additionalAccumulators: AliasedAggregate[]
  ): Pipeline;
```

#### Parameters

| Parameter | Type | Description |
|---|---|---|
| accumulator | [AliasedAggregate](https://firebase.google.com/docs/reference/js/firestore_pipelines.aliasedaggregate.md.txt#aliasedaggregate_class) | The first [AliasedAggregate](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.aliasedaggregate.md.txt#aliasedaggregate_class), wrapping an [AggregateFunction](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.aggregatefunction.md.txt#aggregatefunction_class) and providing a name for the accumulated results. |
| additionalAccumulators | [AliasedAggregate](https://firebase.google.com/docs/reference/js/firestore_pipelines.aliasedaggregate.md.txt#aliasedaggregate_class)\[\] | Optional additional [AliasedAggregate](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.aliasedaggregate.md.txt#aliasedaggregate_class), each wrapping an [AggregateFunction](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.aggregatefunction.md.txt#aggregatefunction_class) and providing a name for the accumulated results. |

**Returns:**

[Pipeline](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipeline_class)

A new Pipeline object with this stage appended to the stage list.

### Example

```typescript
// Calculate the average rating and the total number of books
firestore.pipeline().collection("books")
    .aggregate(
        field("rating").average().as("averageRating"),
        countAll().as("totalBooks")
    );

```

## Pipeline.aggregate()

Performs optionally grouped aggregation operations on the documents from previous stages.

This stage allows you to calculate aggregate values over a set of documents, optionally grouped by one or more fields or functions. You can specify:

- Grouping Fields or Functions: One or more fields or functions to group the documents by. For each distinct combination of values in these fields, a separate group is created. If no grouping fields are provided, a single group containing all documents is used. Not specifying groups is the same as putting the entire inputs into one group.
- Accumulators: One or more accumulation operations to perform within each group. These are defined using \[AliasedAggregate\](./firestore_lite_pipelines.aliasedaggregate#aliasedaggregate_class) expressions, which are typically created by calling \[Expression.as()\](./firestore_lite_pipelines.expression#expressionas) on \[AggregateFunction\](./firestore_lite_pipelines.aggregatefunction#aggregatefunction_class) instances. Each aggregation calculates a value (e.g., sum, average, count) based on the documents within its group.

**Signature:**

```typescript
aggregate(options: AggregateStageOptions): Pipeline;
```

#### Parameters

| Parameter | Type | Description |
|---|---|---|
| options | [AggregateStageOptions](https://firebase.google.com/docs/reference/js/firestore_pipelines.md.txt#aggregatestageoptions) | An object that specifies required and optional parameters for the stage. |

**Returns:**

[Pipeline](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipeline_class)

A new [Pipeline](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.pipeline.md.txt#pipeline_class) object with this stage appended to the stage list.

### Example

```typescript
// Calculate the average rating for each genre.
firestore.pipeline().collection("books")
  .aggregate({
      accumulators: [average(field("rating")).as("avg_rating")],
      groups: ["genre"]
      });

```

## Pipeline.define()

Defines one or more variables in the pipeline's scope. `define` is used to bind a value to a variable for internal reuse within the pipeline body (accessed via the `variable()` function).

This stage is useful for declaring reusable values or intermediate calculations that can be referenced multiple times in later parts of the pipeline, improving readability and maintainability.

Each variable is defined using an [AliasedExpression](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.aliasedexpression.md.txt#aliasedexpression_class), which pairs an expression with a name (alias). The expression can be a simple constant, a field reference, or a complex computation.

**Signature:**

```typescript
define(
    aliasedExpression: AliasedExpression,
    ...additionalExpressions: AliasedExpression[]
  ): Pipeline;
```

#### Parameters

| Parameter | Type | Description |
|---|---|---|
| aliasedExpression | [AliasedExpression](https://firebase.google.com/docs/reference/js/firestore_pipelines.aliasedexpression.md.txt#aliasedexpression_class) | The first expression to bind to a variable. |
| additionalExpressions | [AliasedExpression](https://firebase.google.com/docs/reference/js/firestore_pipelines.aliasedexpression.md.txt#aliasedexpression_class)\[\] | Optional additional expression to bind to a variable. |

**Returns:**

[Pipeline](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipeline_class)

A new Pipeline object with this stage appended to the stage list.

### Example

```typescript
db.pipeline().collection("products")
  .define(
    field("price").multiply(0.9).as("discountedPrice"),
    field("stock").add(10).as("newStock")
  )
  .where(variable("discountedPrice").lessThan(100))
  .select(field("name"), variable("newStock"));

```

## Pipeline.define()

Defines one or more variables in the pipeline's scope. `define` is used to bind a value to a variable for internal reuse within the pipeline body (accessed via the `variable()` function).

This stage is useful for declaring reusable values or intermediate calculations that can be referenced multiple times in later parts of the pipeline, improving readability and maintainability.

Each variable is defined using an [AliasedExpression](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.aliasedexpression.md.txt#aliasedexpression_class), which pairs an expression with a name (alias). The expression can be a simple constant, a field reference, or a complex computation.

**Signature:**

```typescript
define(options: DefineStageOptions): Pipeline;
```

#### Parameters

| Parameter | Type | Description |
|---|---|---|
| options | [DefineStageOptions](https://firebase.google.com/docs/reference/js/firestore_pipelines.md.txt#definestageoptions) | An object that specifies required and optional parameters for the stage. |

**Returns:**

[Pipeline](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipeline_class)

A new Pipeline object with this stage appended to the stage list.

### Example

```typescript
db.pipeline().collection("products")
  .define(
    field("price").multiply(0.9).as("discountedPrice"),
    field("stock").add(10).as("newStock")
  )
  .where(variable("discountedPrice").lessThan(100))
  .select(field("name"), variable("newStock"));

```

## Pipeline.delete()

Performs a delete operation on documents from previous stages.

**Signature:**

```typescript
delete(): Pipeline;
```

**Returns:**

[Pipeline](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipeline_class)

A new [Pipeline](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.pipeline.md.txt#pipeline_class) object with this stage appended to the stage list.

### Example

```typescript
// Deletes all documents in the "books" collection matching condition.
firestore.pipeline().collection("books")
   .where(equal(field("genre"), "Science Fiction"))
   .delete();

```

## Pipeline.delete()

Performs a delete operation on documents from previous stages with options.

**Signature:**

```typescript
delete(options: DeleteStageOptions): Pipeline;
```

#### Parameters

| Parameter | Type | Description |
|---|---|---|
| options | [DeleteStageOptions](https://firebase.google.com/docs/reference/js/firestore_pipelines.md.txt#deletestageoptions) | Options defining how this `DeleteStage` is evaluated. |

**Returns:**

[Pipeline](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipeline_class)

A new [Pipeline](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.pipeline.md.txt#pipeline_class) object with this stage appended to the stage list.

## Pipeline.distinct()

Returns a set of distinct values from the inputs to this stage.

This stage runs through the results from previous stages to include only results with unique combinations of [Expression](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.expression.md.txt#expression_class) values ([Field](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.field.md.txt#field_class), [AliasedExpression](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.aliasedexpression.md.txt#aliasedexpression_class), etc).

The parameters to this stage are defined using [Selectable](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.selectable.md.txt#selectable_interface) expressions or strings:

- \`string\`: Name of an existing field
- \[Field\](./firestore_lite_pipelines.field#field_class): References an existing document field.
- \[AliasedExpression\](./firestore_lite_pipelines.aliasedexpression#aliasedexpression_class): Represents the result of a function with an assigned alias name using \[Expression.as()\](./firestore_lite_pipelines.expression#expressionas).

**Signature:**

```typescript
distinct(
    group: string | Selectable,
    ...additionalGroups: Array<string | Selectable>
  ): Pipeline;
```

#### Parameters

| Parameter | Type | Description |
|---|---|---|
| group | string \| [Selectable](https://firebase.google.com/docs/reference/js/firestore_pipelines.selectable.md.txt#selectable_interface) | The [Selectable](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.selectable.md.txt#selectable_interface) expression or field name to consider when determining distinct value combinations. |
| additionalGroups | Array\<string \| [Selectable](https://firebase.google.com/docs/reference/js/firestore_pipelines.selectable.md.txt#selectable_interface)\> | Optional additional [Selectable](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.selectable.md.txt#selectable_interface) expressions to consider when determining distinct value combinations or strings representing field names. |

**Returns:**

[Pipeline](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipeline_class)

A new [Pipeline](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.pipeline.md.txt#pipeline_class) object with this stage appended to the stage list.

### Example

```typescript
// Get a list of unique author names in uppercase and genre combinations.
firestore.pipeline().collection("books")
    .distinct(toUpper(field("author")).as("authorName"), field("genre"), "publishedAt")
    .select("authorName");

```

## Pipeline.distinct()

Returns a set of distinct values from the inputs to this stage.

This stage runs through the results from previous stages to include only results with unique combinations of [Expression](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.expression.md.txt#expression_class) values ([Field](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.field.md.txt#field_class), [AliasedExpression](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.aliasedexpression.md.txt#aliasedexpression_class), etc).

The parameters to this stage are defined using [Selectable](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.selectable.md.txt#selectable_interface) expressions or strings:

- \`string\`: Name of an existing field
- \[Field\](./firestore_lite_pipelines.field#field_class): References an existing document field.
- \[AliasedExpression\](./firestore_lite_pipelines.aliasedexpression#aliasedexpression_class): Represents the result of a function with an assigned alias name using \[Expression.as()\](./firestore_lite_pipelines.expression#expressionas).

**Signature:**

```typescript
distinct(options: DistinctStageOptions): Pipeline;
```

#### Parameters

| Parameter | Type | Description |
|---|---|---|
| options | [DistinctStageOptions](https://firebase.google.com/docs/reference/js/firestore_pipelines.md.txt#distinctstageoptions) | An object that specifies required and optional parameters for the stage. |

**Returns:**

[Pipeline](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipeline_class)

A new [Pipeline](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.pipeline.md.txt#pipeline_class) object with this stage appended to the stage list.

### Example

```typescript
// Get a list of unique author names in uppercase and genre combinations.
firestore.pipeline().collection("books")
    .distinct(toUpper(field("author")).as("authorName"), field("genre"), "publishedAt")
    .select("authorName");

```

## Pipeline.findNearest()

Performs a vector proximity search on the documents from the previous stage, returning the K-nearest documents based on the specified query `vectorValue` and `distanceMeasure`. The returned documents will be sorted in order from nearest to furthest from the query `vectorValue`.

**Signature:**

```typescript
findNearest(options: FindNearestStageOptions): Pipeline;
```

#### Parameters

| Parameter | Type | Description |
|---|---|---|
| options | [FindNearestStageOptions](https://firebase.google.com/docs/reference/js/firestore_pipelines.md.txt#findneareststageoptions) | An object that specifies required and optional parameters for the stage. |

**Returns:**

[Pipeline](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipeline_class)

A new [Pipeline](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.pipeline.md.txt#pipeline_class) object with this stage appended to the stage list.

### Example

```typescript
// Find the 10 most similar books based on the book description.
const bookDescription = "Lorem ipsum...";
const queryVector: number[] = ...; // compute embedding of `bookDescription`

firestore.pipeline().collection("books")
    .findNearest({
      field: 'embedding',
      vectorValue: queryVector,
      distanceMeasure: 'euclidean',
      limit: 10,                        // optional
      distanceField: 'computedDistance' // optional
    });

```

## Pipeline.insert()

Performs an insert operation using documents from previous stages.

Each input document is inserted at the path in its `__name__` field. The operation fails if a target document already exists. See [InsertStageOptions](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.md.txt#insertstageoptions) for details.

**Signature:**

```typescript
insert(): Pipeline;
```

**Returns:**

[Pipeline](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipeline_class)

A new [Pipeline](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.pipeline.md.txt#pipeline_class) object with this stage appended to the stage list.

## Pipeline.insert()

Performs an insert operation with options.

The operation fails if a target document already exists. See [InsertStageOptions](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.md.txt#insertstageoptions) for how the target path is determined.

**Signature:**

```typescript
insert(options: InsertStageOptions): Pipeline;
```

#### Parameters

| Parameter | Type | Description |
|---|---|---|
| options | [InsertStageOptions](https://firebase.google.com/docs/reference/js/firestore_pipelines.md.txt#insertstageoptions) | Options defining the collection and document ID. |

**Returns:**

[Pipeline](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipeline_class)

A new [Pipeline](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.pipeline.md.txt#pipeline_class) object with this stage appended to the stage list.

## Pipeline.limit()

Limits the maximum number of documents returned by previous stages to `limit`.

This stage is particularly useful when you want to retrieve a controlled subset of data from a potentially large result set. It's often used for:

- Pagination: In combination with \[Pipeline.offset\](./firestore_lite_pipelines.pipeline#pipelineoffset) to retrieve specific pages of results.
- Limiting Data Retrieval: To prevent excessive data transfer and improve performance, especially when dealing with large collections.

**Signature:** \`\`\`typescript limit(limit: number): Pipeline; \`\`\` #### Parameters \| Parameter \| Type \| Description \| \| --- \| --- \| --- \| \| limit \| number \| The maximum number of documents to return. \| **Returns:** \[Pipeline\](./firestore_pipelines.pipeline#pipeline_class) A new Pipeline object with this stage appended to the stage list. ### Example \`\`\`typescript // Limit the results to the top 10 highest-rated books firestore.pipeline().collection('books') .sort(field('rating').descending()) .limit(10); \`\`\` ## Pipeline.limit() Limits the maximum number of documents returned by previous stages to \`limit\`.

This stage is particularly useful when you want to retrieve a controlled subset of data from a potentially large result set. It's often used for:

- Pagination: In combination with \[Pipeline.offset\](./firestore_lite_pipelines.pipeline#pipelineoffset) to retrieve specific pages of results.
- Limiting Data Retrieval: To prevent excessive data transfer and improve performance, especially when dealing with large collections.

**Signature:** \`\`\`typescript limit(options: LimitStageOptions): Pipeline; \`\`\` #### Parameters \| Parameter \| Type \| Description \| \| --- \| --- \| --- \| \| options \| \[LimitStageOptions\](./firestore_pipelines#limitstageoptions) \| An object that specifies required and optional parameters for the stage. \| **Returns:** \[Pipeline\](./firestore_pipelines.pipeline#pipeline_class) A new Pipeline object with this stage appended to the stage list. ### Example \`\`\`typescript // Limit the results to the top 10 highest-rated books firestore.pipeline().collection('books') .sort(field('rating').descending()) .limit(10); \`\`\` ## Pipeline.offset() Skips the first \`offset\` number of documents from the results of previous stages.

This stage is useful for implementing pagination in your pipelines, allowing you to retrieve results in chunks. It is typically used in conjunction with \[Pipeline.limit\](./firestore_lite_pipelines.pipeline#pipelinelimit) to control the size of each page.

**Signature:**

\`\`\`typescript
offset(offset: number): Pipeline;
\`\`\`

#### Parameters

\| Parameter \| Type \| Description \|
\| --- \| --- \| --- \|
\| offset \| number \| The number of documents to skip. \|

**Returns:**

\[Pipeline\](./firestore_pipelines.pipeline#pipeline_class)

A new Pipeline object with this stage appended to the stage list.

### Example


\`\`\`typescript
// Retrieve the second page of 20 results
firestore.pipeline().collection('books')
.sort(field('published').descending())
.offset(20) // Skip the first 20 results
.limit(20); // Take the next 20 results

\`\`\`

## Pipeline.offset()

Skips the first \`offset\` number of documents from the results of previous stages.

This stage is useful for implementing pagination in your pipelines, allowing you to retrieve results in chunks. It is typically used in conjunction with \[Pipeline.limit\](./firestore_lite_pipelines.pipeline#pipelinelimit) to control the size of each page.

**Signature:**

\`\`\`typescript
offset(options: OffsetStageOptions): Pipeline;
\`\`\`

#### Parameters

\| Parameter \| Type \| Description \|
\| --- \| --- \| --- \|
\| options \| \[OffsetStageOptions\](./firestore_pipelines#offsetstageoptions) \| An object that specifies required and optional parameters for the stage. \|

**Returns:**

\[Pipeline\](./firestore_pipelines.pipeline#pipeline_class)

A new Pipeline object with this stage appended to the stage list.

### Example


\`\`\`typescript
// Retrieve the second page of 20 results
firestore.pipeline().collection('books')
.sort(field('published').descending())
.offset(20) // Skip the first 20 results
.limit(20); // Take the next 20 results

\`\`\`

## Pipeline.rawStage()

Adds a raw stage to the pipeline.

This method provides a flexible way to extend the pipeline's functionality by adding custom stages. Each raw stage is defined by a unique \`name\` and a set of \`params\` that control its behavior.

Example (Assuming there is no 'where' stage available in SDK):

**Signature:**

\`\`\`typescript
rawStage(
name: string,
params: unknown\[\],
options?: {
\[key: string\]: Expression \| unknown;
}
): Pipeline;
\`\`\`

#### Parameters

\| Parameter \| Type \| Description \|
\| --- \| --- \| --- \|
\| name \| string \| The unique name of the raw stage to add. \|
\| params \| unknown\\\[\\\] \| A list of parameters to configure the raw stage's behavior. \|
\| options \| { \\\[key: string\\\]: \[Expression\](./firestore_pipelines.expression#expression_class) \\\| unknown; } \| An object of key value pairs that specifies optional parameters for the stage. \|

**Returns:**

\[Pipeline\](./firestore_pipelines.pipeline#pipeline_class)

A new \[Pipeline\](./firestore_lite_pipelines.pipeline#pipeline_class) object with this stage appended to the stage list.

### Example


\`\`\`typescript
// Assume we don't have a built-in 'where' stage
firestore.pipeline().collection('books')
.rawStage('where', \[field('published').lessThan(1900)\]) // Custom 'where' stage
.select('title', 'author');

\`\`\`

## Pipeline.removeFields()

Remove fields from outputs of previous stages.

**Signature:**

\`\`\`typescript
removeFields(
fieldValue: Field \| string,
...additionalFields: Array ): Pipeline; \`\`\` #### Parameters \| Parameter \| Type \| Description \| \| --- \| --- \| --- \| \| fieldValue \| \[Field\](./firestore_pipelines.field#field_class) \\\| string \| The first field to remove. \| \| additionalFields \| Array\<\[Field\](./firestore_pipelines.field#field_class) \\\| string\> \| Optional additional fields to remove. \| **Returns:** \[Pipeline\](./firestore_pipelines.pipeline#pipeline_class) A new Pipeline object with this stage appended to the stage list. ### Example \`\`\`typescript firestore.pipeline().collection('books') // removes field 'rating' and 'cost' from the previous stage outputs. .removeFields( field('rating'), 'cost' ); \`\`\` ## Pipeline.removeFields() Remove fields from outputs of previous stages. **Signature:** \`\`\`typescript removeFields(options: RemoveFieldsStageOptions): Pipeline; \`\`\` #### Parameters \| Parameter \| Type \| Description \| \| --- \| --- \| --- \| \| options \| \[RemoveFieldsStageOptions\](./firestore_pipelines#removefieldsstageoptions) \| An object that specifies required and optional parameters for the stage. \| **Returns:** \[Pipeline\](./firestore_pipelines.pipeline#pipeline_class) A new Pipeline object with this stage appended to the stage list. ### Example \`\`\`typescript firestore.pipeline().collection('books') // removes field 'rating' and 'cost' from the previous stage outputs. .removeFields( field('rating'), 'cost' ); \`\`\` ## Pipeline.replaceWith() Fully overwrites all fields in a document with those coming from a nested map.

This stage allows you to emit a map value as a document. Each key of the map becomes a field on the document that contains the corresponding value.

**Signature:**

\`\`\`typescript
replaceWith(fieldName: string): Pipeline;
\`\`\`

#### Parameters

\| Parameter \| Type \| Description \|
\| --- \| --- \| --- \|
\| fieldName \| string \| The \[Field\](./firestore_lite_pipelines.field#field_class) field containing the nested map. \|

**Returns:**

\[Pipeline\](./firestore_pipelines.pipeline#pipeline_class)

A new \[Pipeline\](./firestore_lite_pipelines.pipeline#pipeline_class) object with this stage appended to the stage list.

### Example


\`\`\`typescript
// Input.
// {
// 'name': 'John Doe Jr.',
// 'parents': {
// 'father': 'John Doe Sr.',
// 'mother': 'Jane Doe'
// }
// }

// Emit parents as document.
firestore.pipeline().collection('people').replaceWith('parents');

// Output
// {
// 'father': 'John Doe Sr.',
// 'mother': 'Jane Doe'
// }

\`\`\`

## Pipeline.replaceWith()

Fully overwrites all fields in a document with those coming from a map.

This stage allows you to emit a map value as a document. Each key of the map becomes a field on the document that contains the corresponding value.

**Signature:**

\`\`\`typescript
replaceWith(expr: Expression): Pipeline;
\`\`\`

#### Parameters

\| Parameter \| Type \| Description \|
\| --- \| --- \| --- \|
\| expr \| \[Expression\](./firestore_pipelines.expression#expression_class) \| An \[Expression\](./firestore_lite_pipelines.expression#expression_class) that when returned evaluates to a map. \|

**Returns:**

\[Pipeline\](./firestore_pipelines.pipeline#pipeline_class)

A new \[Pipeline\](./firestore_lite_pipelines.pipeline#pipeline_class) object with this stage appended to the stage list.

### Example


\`\`\`typescript
// Input.
// {
// 'name': 'John Doe Jr.',
// 'parents': {
// 'father': 'John Doe Sr.',
// 'mother': 'Jane Doe'
// }
// }

// Emit parents as document.
firestore.pipeline().collection('people').replaceWith(map({
foo: 'bar',
info: {
name: field('name')
}
}));

// Output
// {
// 'father': 'John Doe Sr.',
// 'mother': 'Jane Doe'
// }

\`\`\`

## Pipeline.replaceWith()

Fully overwrites all fields in a document with those coming from a map.

This stage allows you to emit a map value as a document. Each key of the map becomes a field on the document that contains the corresponding value.

**Signature:**

\`\`\`typescript
replaceWith(options: ReplaceWithStageOptions): Pipeline;
\`\`\`

#### Parameters

\| Parameter \| Type \| Description \|
\| --- \| --- \| --- \|
\| options \| \[ReplaceWithStageOptions\](./firestore_pipelines#replacewithstageoptions) \| An object that specifies required and optional parameters for the stage. \|

**Returns:**

\[Pipeline\](./firestore_pipelines.pipeline#pipeline_class)

A new \[Pipeline\](./firestore_lite_pipelines.pipeline#pipeline_class) object with this stage appended to the stage list.

### Example


\`\`\`typescript
// Input.
// {
// 'name': 'John Doe Jr.',
// 'parents': {
// 'father': 'John Doe Sr.',
// 'mother': 'Jane Doe'
// }
// }

// Emit parents as document.
firestore.pipeline().collection('people').replaceWith(map({
foo: 'bar',
info: {
name: field('name')
}
}));

// Output
// {
// 'father': 'John Doe Sr.',
// 'mother': 'Jane Doe'
// }

\`\`\`

## Pipeline.sample()

Performs a pseudo-random sampling of the documents from the previous stage.

This stage will filter documents pseudo-randomly. The parameter specifies how number of documents to be returned.

Examples:

**Signature:**

\`\`\`typescript
sample(documents: number): Pipeline;
\`\`\`

#### Parameters

\| Parameter \| Type \| Description \|
\| --- \| --- \| --- \|
\| documents \| number \| The number of documents to sample. \|

**Returns:**

\[Pipeline\](./firestore_pipelines.pipeline#pipeline_class)

A new \[Pipeline\](./firestore_lite_pipelines.pipeline#pipeline_class) object with this stage appended to the stage list.

### Example


\`\`\`typescript
// Sample 25 books, if available.
firestore.pipeline().collection('books')
.sample(25);

\`\`\`

## Pipeline.sample()

Performs a pseudo-random sampling of the documents from the previous stage.

This stage will filter documents pseudo-randomly. The 'options' parameter specifies how sampling will be performed. See \[SampleStageOptions\](./firestore_lite_pipelines#samplestageoptions) for more information.

**Signature:**

\`\`\`typescript
sample(options: SampleStageOptions): Pipeline;
\`\`\`

#### Parameters

\| Parameter \| Type \| Description \|
\| --- \| --- \| --- \|
\| options \| \[SampleStageOptions\](./firestore_pipelines#samplestageoptions) \| An object that specifies required and optional parameters for the stage. \|

**Returns:**

\[Pipeline\](./firestore_pipelines.pipeline#pipeline_class)

A new \[Pipeline\](./firestore_lite_pipelines.pipeline#pipeline_class) object with this stage appended to the stage list.

### Example


\`\`\`typescript
// Sample 10 books, if available.
firestore.pipeline().collection("books")
.sample({ documents: 10 });

// Sample 50% of books.
firestore.pipeline().collection("books")
.sample({ percentage: 0.5 });

\`\`\`

## Pipeline.search()

Add a search stage to the Pipeline. The search stage supports full-text search and geo search expressions.

This must be the first stage of the pipeline. A limited set of expressions are supported in the search stage.

**Signature:**

\`\`\`typescript
search(options: SearchStageOptions): Pipeline;
\`\`\`

#### Parameters

\| Parameter \| Type \| Description \|
\| --- \| --- \| --- \|
\| options \| \[SearchStageOptions\](./firestore_pipelines#searchstageoptions) \| An object that specifies parameters for the stage. A new `Pipeline` object with this stage appended to the stage list. \|

**Returns:**

\[Pipeline\](./firestore_pipelines.pipeline#pipeline_class)

### Example 1


\`\`\`typescript
// Full-text search example
firestore.pipeline().collection("restaurants")
.search({
query: documentMatches("waffles OR pancakes"),
sort: \[
score().descending(),
\],
addFields: \[
score().as("searchScore"),
\]
})

\`\`\`

### Example 2


\`\`\`typescript
// Geo distance search example
const queryLocation = new GeoPoint(0, 0);
db.pipeline().collection('restaurants').search({
query: field('location').geoDistance(queryLocation).lessThanOrEqual(1000),
sort: \[
score().descending(),
\],
})

\`\`\`

## Pipeline.select()

Selects or creates a set of fields from the outputs of previous stages.

The selected fields are defined using \[Selectable\](./firestore_lite_pipelines.selectable#selectable_interface) expressions, which can be:

- \`string\` : Name of an existing field
- \[Field\](./firestore_lite_pipelines.field#field_class): References an existing field.
- \[AliasedExpression\](./firestore_lite_pipelines.aliasedexpression#aliasedexpression_class): Represents the result of a function with an assigned alias name using \[Expression.as()\](./firestore_lite_pipelines.expression#expressionas)

If no selections are provided, the output of this stage is empty. Use \[Pipeline.addFields()\](./firestore_lite_pipelines.pipeline#pipelineaddfields) instead if only additions are desired.

**Signature:**

\`\`\`typescript
select(
selection: Selectable \| string,
...additionalSelections: Array ): Pipeline; \`\`\` #### Parameters \| Parameter \| Type \| Description \| \| --- \| --- \| --- \| \| selection \| \[Selectable\](./firestore_pipelines.selectable#selectable_interface) \\\| string \| The first field to include in the output documents, specified as \[Selectable\](./firestore_lite_pipelines.selectable#selectable_interface) expression or string value representing the field name. \| \| additionalSelections \| Array\<\[Selectable\](./firestore_pipelines.selectable#selectable_interface) \\\| string\> \| Optional additional fields to include in the output documents, specified as \[Selectable\](./firestore_lite_pipelines.selectable#selectable_interface) expressions or `string` values representing field names. \| **Returns:** \[Pipeline\](./firestore_pipelines.pipeline#pipeline_class) A new Pipeline object with this stage appended to the stage list. ### Example \`\`\`typescript db.pipeline().collection("books") .select( "firstName", field("lastName"), field("address").toUpper().as("upperAddress"), ); \`\`\` ## Pipeline.select() Selects or creates a set of fields from the outputs of previous stages.

The selected fields are defined using \[Selectable\](./firestore_lite_pipelines.selectable#selectable_interface) expressions, which can be:

- \`string\`: Name of an existing field
- \[Field\](./firestore_lite_pipelines.field#field_class): References an existing field.
- \[AliasedExpression\](./firestore_lite_pipelines.aliasedexpression#aliasedexpression_class): Represents the result of a function with an assigned alias name using \[Expression.as()\](./firestore_lite_pipelines.expression#expressionas)

If no selections are provided, the output of this stage is empty. Use \[Pipeline.addFields()\](./firestore_lite_pipelines.pipeline#pipelineaddfields) instead if only additions are desired.

**Signature:**

\`\`\`typescript
select(options: SelectStageOptions): Pipeline;
\`\`\`

#### Parameters

\| Parameter \| Type \| Description \|
\| --- \| --- \| --- \|
\| options \| \[SelectStageOptions\](./firestore_pipelines#selectstageoptions) \| An object that specifies required and optional parameters for the stage. \|

**Returns:**

\[Pipeline\](./firestore_pipelines.pipeline#pipeline_class)

A new Pipeline object with this stage appended to the stage list.

### Example


\`\`\`typescript
db.pipeline().collection("books")
.select(
"firstName",
field("lastName"),
field("address").toUpper().as("upperAddress"),
);

\`\`\`

## Pipeline.sort()

Sorts the documents from previous stages based on one or more \[Ordering\](./firestore_lite_pipelines.ordering#ordering_class) criteria.

This stage allows you to order the results of your pipeline. You can specify multiple \[Ordering\](./firestore_lite_pipelines.ordering#ordering_class) instances to sort by multiple fields in ascending or descending order. If documents have the same value for a field used for sorting, the next specified ordering will be used. If all orderings result in equal comparison, the documents are considered equal and the order is unspecified.

**Signature:**

\`\`\`typescript
sort(ordering: Ordering, ...additionalOrderings: Ordering\[\]): Pipeline;
\`\`\`

#### Parameters

\| Parameter \| Type \| Description \|
\| --- \| --- \| --- \|
\| ordering \| \[Ordering\](./firestore_pipelines.ordering#ordering_class) \| The first \[Ordering\](./firestore_lite_pipelines.ordering#ordering_class) instance specifying the sorting criteria. \|
\| additionalOrderings \| \[Ordering\](./firestore_pipelines.ordering#ordering_class)\\\[\\\] \| Optional additional \[Ordering\](./firestore_lite_pipelines.ordering#ordering_class) instances specifying the additional sorting criteria. \|

**Returns:**

\[Pipeline\](./firestore_pipelines.pipeline#pipeline_class)

A new \[Pipeline\](./firestore_lite_pipelines.pipeline#pipeline_class) object with this stage appended to the stage list.

### Example


\`\`\`typescript
// Sort books by rating in descending order, and then by title in ascending order for books
// with the same rating
firestore.pipeline().collection("books")
.sort(
field("rating").descending(),
field("title").ascending()
);

\`\`\`

## Pipeline.sort()

Sorts the documents from previous stages based on one or more \[Ordering\](./firestore_lite_pipelines.ordering#ordering_class) criteria.

This stage allows you to order the results of your pipeline. You can specify multiple \[Ordering\](./firestore_lite_pipelines.ordering#ordering_class) instances to sort by multiple fields in ascending or descending order. If documents have the same value for a field used for sorting, the next specified ordering will be used. If all orderings result in equal comparison, the documents are considered equal and the order is unspecified.

**Signature:**

\`\`\`typescript
sort(options: SortStageOptions): Pipeline;
\`\`\`

#### Parameters

\| Parameter \| Type \| Description \|
\| --- \| --- \| --- \|
\| options \| \[SortStageOptions\](./firestore_pipelines#sortstageoptions) \| An object that specifies required and optional parameters for the stage. \|

**Returns:**

\[Pipeline\](./firestore_pipelines.pipeline#pipeline_class)

A new \[Pipeline\](./firestore_lite_pipelines.pipeline#pipeline_class) object with this stage appended to the stage list.

### Example


\`\`\`typescript
// Sort books by rating in descending order, and then by title in ascending order for books
// with the same rating
firestore.pipeline().collection("books")
.sort(
field("rating").descending(),
field("title").ascending()
);

\`\`\`

## Pipeline.toArrayExpression()

Converts this Pipeline into an expression that evaluates to an array of results.

Result Unwrapping:

- If the items have a single field, their values are unwrapped and returned directly in the array.
- If the items have multiple fields, they are returned as objects in the array

**Signature:** \`\`\`typescript toArrayExpression(): Expression; \`\`\` **Returns:** \[Expression\](./firestore_pipelines.expression#expression_class) An \`Expression\` representing the execution of this pipeline. ### Example \`\`\`typescript // Get a list of reviewers for each book db.pipeline().collection("books") .define(field("id").as("book_id")) .addFields( db.pipeline().collection("reviews") .where(field("book_id").equal(variable("book_id"))) .select(field("reviewer")) .toArrayExpression() .as("reviewers") ) \`\`\` Output: \`\`\`json \[ { "id": "1", "title": "1984", "reviewers": \["Alice", "Bob"\] } \] \`\`\` Multiple Fields: \`\`\`typescript // Get a list of reviews (reviewer and rating) for each book db.pipeline().collection("books") .define(field("id").as("book_id")) .addFields( db.pipeline().collection("reviews") .where(field("book_id").equal(variable("book_id"))) .select(field("reviewer"), field("rating")) .toArrayExpression() .as("reviews")) \`\`\` Output: \`\`\`json \[ { "id": "1", "title": "1984", "reviews": \[ { "reviewer": "Alice", "rating": 5 }, { "reviewer": "Bob", "rating": 4 } \] } \] \`\`\` ## Pipeline.toScalarExpression() Converts this Pipeline into an expression that evaluates to a single scalar result.

**Runtime Validation:** The runtime validates that the result set contains zero or one item. If zero items, it evaluates to \`null\`.

<br />

Result Unwrapping:

- If the item has a single field, its value is unwrapped and returned directly.
- If the item has multiple fields, they are returned as an object.

<br />

**Signature:**

```typescript
toScalarExpression(): Expression;
```

**Returns:**

[Expression](https://firebase.google.com/docs/reference/js/firestore_pipelines.expression.md.txt#expression_class)

An `Expression` representing the execution of this pipeline.

### Example

```typescript
// Calculate average rating for a restaurant
db.pipeline().collection("restaurants").addFields(
  db.pipeline().collection("reviews")
    .where(field("restaurant_id").equal(variable("rid")))
    .aggregate(average("rating").as("avg"))
    // Unwraps the single "avg" field to a scalar double
    .toScalarExpression().as("average_rating")
)

```

Output:

```json
{
  "name": "The Burger Joint",
  "average_rating": 4.5
}

```

Multiple Fields:

```typescript
// Calculate average rating AND count for a restaurant
db.pipeline().collection("restaurants").addFields(
  db.pipeline().collection("reviews")
    .where(field("restaurant_id").equal(variable("rid")))
    .aggregate(
      average("rating").as("avg"),
      count().as("count")
    )
    // Returns an object with "avg" and "count" fields
    .toScalarExpression().as("stats")
)

```

Output:

```json
{
  "name": "The Burger Joint",
  "stats": {
    "avg": 4.5,
    "count": 100
  }
}

```

## Pipeline.union()

Performs union of all documents from two pipelines, including duplicates.

<br />

This stage will pass through documents from previous stage, and also pass through documents from previous stage of the `other` [Pipeline](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.pipeline.md.txt#pipeline_class) given in parameter. The order of documents emitted from this stage is undefined.

**Signature:**

```typescript
union(other: Pipeline): Pipeline;
```

#### Parameters

| Parameter | Type | Description |
|---|---|---|
| other | [Pipeline](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipeline_class) | The other [Pipeline](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.pipeline.md.txt#pipeline_class) that is part of union. |

**Returns:**

[Pipeline](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipeline_class)

A new [Pipeline](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.pipeline.md.txt#pipeline_class) object with this stage appended to the stage list.

### Example

```typescript
// Emit documents from books collection and magazines collection.
firestore.pipeline().collection('books')
    .union(firestore.pipeline().collection('magazines'));

```

## Pipeline.union()

Performs union of all documents from two pipelines, including duplicates.

<br />

This stage will pass through documents from previous stage, and also pass through documents from previous stage of the `other` [Pipeline](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.pipeline.md.txt#pipeline_class) given in parameter. The order of documents emitted from this stage is undefined.

**Signature:**

```typescript
union(options: UnionStageOptions): Pipeline;
```

#### Parameters

| Parameter | Type | Description |
|---|---|---|
| options | [UnionStageOptions](https://firebase.google.com/docs/reference/js/firestore_pipelines.md.txt#unionstageoptions) | An object that specifies required and optional parameters for the stage. |

**Returns:**

[Pipeline](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipeline_class)

A new [Pipeline](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.pipeline.md.txt#pipeline_class) object with this stage appended to the stage list.

### Example

```typescript
// Emit documents from books collection and magazines collection.
firestore.pipeline().collection('books')
    .union(firestore.pipeline().collection('magazines'));

```

## Pipeline.unnest()

Produces a document for each element in an input array.

For each previous stage document, this stage will emit zero or more augmented documents. The input array specified by the `selectable` parameter, will emit an augmented document for each input array element. The input array element will augment the previous stage document by setting the `alias` field with the array element value.

When `selectable` evaluates to a non-array value (ex: number, null, absent), then the stage becomes a no-op for the current input document, returning it as is with the `alias` field absent.

No documents are emitted when `selectable` evaluates to an empty array.

**Signature:**

```typescript
unnest(selectable: Selectable, indexField?: string): Pipeline;
```

#### Parameters

| Parameter | Type | Description |
|---|---|---|
| selectable | [Selectable](https://firebase.google.com/docs/reference/js/firestore_pipelines.selectable.md.txt#selectable_interface) | A selectable expression defining the field to unnest and the alias to use for each un-nested element in the output documents. |
| indexField | string | An optional string value specifying the field path to write the offset (starting at zero) into the array the un-nested element is from |

**Returns:**

[Pipeline](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipeline_class)

A new [Pipeline](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.pipeline.md.txt#pipeline_class) object with this stage appended to the stage list.

### Example

```typescript
// Input:
// { "title": "The Hitchhiker's Guide to the Galaxy", "tags": [ "comedy", "space", "adventure" ], ... }

// Emit a book document for each tag of the book.
firestore.pipeline().collection("books")
    .unnest(field("tags").as('tag'), 'tagIndex');

// Output:
// { "title": "The Hitchhiker's Guide to the Galaxy", "tag": "comedy", "tagIndex": 0, ... }
// { "title": "The Hitchhiker's Guide to the Galaxy", "tag": "space", "tagIndex": 1, ... }
// { "title": "The Hitchhiker's Guide to the Galaxy", "tag": "adventure", "tagIndex": 2, ... }

```

## Pipeline.unnest()

Produces a document for each element in an input array.

For each previous stage document, this stage will emit zero or more augmented documents. The input array specified by the `selectable` parameter, will emit an augmented document for each input array element. The input array element will augment the previous stage document by setting the `alias` field with the array element value.

When `selectable` evaluates to a non-array value (ex: number, null, absent), then the stage becomes a no-op for the current input document, returning it as is with the `alias` field absent.

No documents are emitted when `selectable` evaluates to an empty array.

**Signature:**

```typescript
unnest(options: UnnestStageOptions): Pipeline;
```

#### Parameters

| Parameter | Type | Description |
|---|---|---|
| options | [UnnestStageOptions](https://firebase.google.com/docs/reference/js/firestore_pipelines.md.txt#unneststageoptions) | An object that specifies required and optional parameters for the stage. |

**Returns:**

[Pipeline](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipeline_class)

A new [Pipeline](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.pipeline.md.txt#pipeline_class) object with this stage appended to the stage list.

### Example

```typescript
// Input:
// { "title": "The Hitchhiker's Guide to the Galaxy", "tags": [ "comedy", "space", "adventure" ], ... }

// Emit a book document for each tag of the book.
firestore.pipeline().collection("books")
    .unnest(field("tags").as('tag'), 'tagIndex');

// Output:
// { "title": "The Hitchhiker's Guide to the Galaxy", "tag": "comedy", "tagIndex": 0, ... }
// { "title": "The Hitchhiker's Guide to the Galaxy", "tag": "space", "tagIndex": 1, ... }
// { "title": "The Hitchhiker's Guide to the Galaxy", "tag": "adventure", "tagIndex": 2, ... }

```

## Pipeline.update()

Performs an update operation using documents from previous stages.

Each input document is written to the path in its `__name__` field. See [UpdateStageOptions](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.md.txt#updatestageoptions) for details.

**Signature:**

```typescript
update(): Pipeline;
```

**Returns:**

[Pipeline](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipeline_class)

A new [Pipeline](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.pipeline.md.txt#pipeline_class) object with this stage appended to the stage list.

## Pipeline.update()

Performs an update operation using documents from previous stages.

Each input document is written to the path in its `__name__` field. See [UpdateStageOptions](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.md.txt#updatestageoptions) for details.

**Signature:**

```typescript
update(
    transformedField: AliasedExpression,
    ...additionalFields: AliasedExpression[]
  ): Pipeline;
```

#### Parameters

| Parameter | Type | Description |
|---|---|---|
| transformedField | [AliasedExpression](https://firebase.google.com/docs/reference/js/firestore_pipelines.aliasedexpression.md.txt#aliasedexpression_class) | The first transformation to apply. |
| additionalFields | [AliasedExpression](https://firebase.google.com/docs/reference/js/firestore_pipelines.aliasedexpression.md.txt#aliasedexpression_class)\[\] | Additional transformations to apply. |

**Returns:**

[Pipeline](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipeline_class)

A new [Pipeline](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.pipeline.md.txt#pipeline_class) object with this stage appended to the stage list.

## Pipeline.update()

Performs an update operation with options.

**Signature:**

```typescript
update(options: UpdateStageOptions): Pipeline;
```

#### Parameters

| Parameter | Type | Description |
|---|---|---|
| options | [UpdateStageOptions](https://firebase.google.com/docs/reference/js/firestore_pipelines.md.txt#updatestageoptions) | Options defining how this `UpdateStage` is evaluated and specifying the fields to update or add to each document. |

**Returns:**

[Pipeline](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipeline_class)

A new [Pipeline](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.pipeline.md.txt#pipeline_class) object with this stage appended to the stage list.

## Pipeline.upsert()

Performs an upsert operation using documents from previous stages.

Each input document is written to the path in its `__name__` field. See [UpsertStageOptions](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.md.txt#upsertstageoptions) for details.

**Signature:**

```typescript
upsert(): Pipeline;
```

**Returns:**

[Pipeline](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipeline_class)

A new [Pipeline](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.pipeline.md.txt#pipeline_class) object with this stage appended to the stage list.

## Pipeline.upsert()

Performs an upsert operation using documents from previous stages.

Each input document is written to the path in its `__name__` field. See [UpsertStageOptions](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.md.txt#upsertstageoptions) for details.

**Signature:**

```typescript
upsert(
    additionalField: AliasedExpression,
    ...additionalFields: AliasedExpression[]
  ): Pipeline;
```

#### Parameters

| Parameter | Type | Description |
|---|---|---|
| additionalField | [AliasedExpression](https://firebase.google.com/docs/reference/js/firestore_pipelines.aliasedexpression.md.txt#aliasedexpression_class) | The first additional field to apply. |
| additionalFields | [AliasedExpression](https://firebase.google.com/docs/reference/js/firestore_pipelines.aliasedexpression.md.txt#aliasedexpression_class)\[\] | Additional fields to apply. |

**Returns:**

[Pipeline](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipeline_class)

A new [Pipeline](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.pipeline.md.txt#pipeline_class) object with this stage appended to the stage list.

## Pipeline.upsert()

Performs an upsert operation with options.

See [UpsertStageOptions](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.md.txt#upsertstageoptions) for how the target path is determined.

**Signature:**

```typescript
upsert(options: UpsertStageOptions): Pipeline;
```

#### Parameters

| Parameter | Type | Description |
|---|---|---|
| options | [UpsertStageOptions](https://firebase.google.com/docs/reference/js/firestore_pipelines.md.txt#upsertstageoptions) | Options defining the target collection, document ID, and additional fields. |

**Returns:**

[Pipeline](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipeline_class)

A new [Pipeline](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.pipeline.md.txt#pipeline_class) object with this stage appended to the stage list.

## Pipeline.where()

Filters the documents from previous stages to only include those matching the specified [BooleanExpression](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.booleanexpression.md.txt#booleanexpression_class).

<br />

This stage allows you to apply conditions to the data, similar to a "WHERE" clause in SQL. You can filter documents based on their field values, using implementations of [BooleanExpression](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.booleanexpression.md.txt#booleanexpression_class), typically including but not limited to:

- field comparators: \[Expression.equal()\](./firestore_lite_pipelines.expression#expressionequal), \[Expression.lessThan()\](./firestore_lite_pipelines.expression#expressionlessthan), \[Expression.greaterThan()\](./firestore_lite_pipelines.expression#expressiongreaterthan), etc.
- logical operators: \[and\](./firestore#and_e72c712), \[or\](./firestore#or_e72c712), \[not\](./firestore_lite_pipelines#not_c5b8fb1), etc.
- advanced functions: \[Expression.regexMatch()\](./firestore_lite_pipelines.expression#expressionregexmatch), \[Expression.arrayContains()\](./firestore_lite_pipelines.expression#expressionarraycontains), etc.

**Signature:**

```typescript
where(condition: BooleanExpression): Pipeline;
```

#### Parameters

| Parameter | Type | Description |
|---|---|---|
| condition | [BooleanExpression](https://firebase.google.com/docs/reference/js/firestore_pipelines.booleanexpression.md.txt#booleanexpression_class) | The [BooleanExpression](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.booleanexpression.md.txt#booleanexpression_class) to apply. |

**Returns:**

[Pipeline](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipeline_class)

A new Pipeline object with this stage appended to the stage list.

### Example

```typescript
firestore.pipeline().collection("books")
  .where(
    and(
        greaterThan(field("rating"), 4.0),   // Filter for ratings greater than 4.0
        field("genre").equal("Science Fiction") // Equivalent to equal("genre", "Science Fiction")
    )
  );

```

## Pipeline.where()

Filters the documents from previous stages to only include those matching the specified [BooleanExpression](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.booleanexpression.md.txt#booleanexpression_class).

<br />

This stage allows you to apply conditions to the data, similar to a "WHERE" clause in SQL. You can filter documents based on their field values, using implementations of [BooleanExpression](https://firebase.google.com/docs/reference/js/firestore_lite_pipelines.booleanexpression.md.txt#booleanexpression_class), typically including but not limited to:

- field comparators: \[Expression.equal()\](./firestore_lite_pipelines.expression#expressionequal), \[Expression.lessThan()\](./firestore_lite_pipelines.expression#expressionlessthan) (less than), \[Expression.greaterThan()\](./firestore_lite_pipelines.expression#expressiongreaterthan), etc.
- logical operators: \[and\](./firestore#and_e72c712), \[or\](./firestore#or_e72c712), \[not\](./firestore_lite_pipelines#not_c5b8fb1), etc.
- advanced functions: \[Expression.regexMatch()\](./firestore_lite_pipelines.expression#expressionregexmatch), \[Expression.arrayContains()\](./firestore_lite_pipelines.expression#expressionarraycontains), etc.

**Signature:**

```typescript
where(options: WhereStageOptions): Pipeline;
```

#### Parameters

| Parameter | Type | Description |
|---|---|---|
| options | [WhereStageOptions](https://firebase.google.com/docs/reference/js/firestore_pipelines.md.txt#wherestageoptions) | An object that specifies required and optional parameters for the stage. |

**Returns:**

[Pipeline](https://firebase.google.com/docs/reference/js/firestore_pipelines.pipeline.md.txt#pipeline_class)

A new Pipeline object with this stage appended to the stage list.

### Example

```typescript
firestore.pipeline().collection("books")
  .where(
    and(
        greaterThan(field("rating"), 4.0),   // Filter for ratings greater than 4.0
        field("genre").equal("Science Fiction") // Equivalent to equal("genre", "Science Fiction")
    )
  );

```