Back to Firebase Js Sdk

Pipeline class

docs-devsite/firestore_pipelines.pipeline.md

12.12.148.0 KB
Original Source

Project: /docs/reference/js/_project.yaml Book: /docs/reference/_book.yaml page_type: reference

{% comment %} DO NOT EDIT THIS FILE! This is generated by the JS SDK team, and any local changes will be overwritten. Changes should be made in the source code at https://github.com/firebase/firebase-js-sdk {% endcomment %}

Pipeline class

<b>Signature:</b>

typescript
export declare class Pipeline 

Methods

MethodModifiersDescription
addFields(field, additionalFields)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<!-- -->s, which can be:<!-- -->- Field<!-- -->: References an existing document field. - Expression<!-- -->: Either a literal value (see constant()<!-- -->) or a computed value with an assigned alias using Expression.as()<!-- -->.<!-- -->Example:
addFields(options)
aggregate(accumulator, additionalAccumulators)Performs aggregation operations on the documents from previous stages.<p>This stage allows you to calculate aggregate values over a set of documents. You define the aggregations to perform using AliasedAggregate expressions which are typically results of calling Expression.as() on AggregateFunction instances.<p>Example:
aggregate(options)Performs optionally grouped aggregation operations on the documents from previous stages.<p>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:<ul> <li>**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.</li> <li>**Accumulators:** One or more accumulation operations to perform within each group. These are defined using AliasedAggregate expressions, which are typically created by calling Expression.as() on AggregateFunction instances. Each aggregation calculates a value (e.g., sum, average, count) based on the documents within its group.</li> </ul><p>Example:
define(aliasedExpression, additionalExpressions)
define(options)
distinct(group, additionalGroups)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 values (Field<!-- -->, AliasedExpression<!-- -->, etc).<!-- -->The parameters to this stage are defined using Selectable expressions or strings:<!-- -->- <code>string</code>: Name of an existing field - Field<!-- -->: References an existing document field. - AliasedExpression<!-- -->: Represents the result of a function with an assigned alias name using Expression.as()<!-- -->.<!-- -->Example:
distinct(options)
findNearest(options)Performs a vector proximity search on the documents from the previous stage, returning the K-nearest documents based on the specified query <code>vectorValue</code> and <code>distanceMeasure</code>. The returned documents will be sorted in order from nearest to furthest from the query <code>vectorValue</code>.<p>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
});

| | limit(limit) | | Limits the maximum number of documents returned by previous stages to <code>limit</code>.<p>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:<ul> <li>**Pagination:** In combination with to retrieve specific pages of results.</li> <li>**Limiting Data Retrieval:** To prevent excessive data transfer and improve performance, especially when dealing with large collections.</li> </ul><p>Example: | | limit(options) | | | | offset(offset) | | Skips the first <code>offset</code> number of documents from the results of previous stages.<p>This stage is useful for implementing pagination in your pipelines, allowing you to retrieve results in chunks. It is typically used in conjunction with to control the size of each page.<p>Example: | | offset(options) | | | | rawStage(name, params, options) | | Adds a raw stage to the pipeline.<p>This method provides a flexible way to extend the pipeline's functionality by adding custom stages. Each raw stage is defined by a unique <code>name</code> and a set of <code>params</code> that control its behavior.<p>Example (Assuming there is no 'where' stage available in SDK): | | removeFields(fieldValue, additionalFields) | | Remove fields from outputs of previous stages.<!-- -->Example: | | removeFields(options) | | | | replaceWith(fieldName) | | Fully overwrites all fields in a document with those coming from a nested map.<p>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.<p>Example: | | replaceWith(expr) | | Fully overwrites all fields in a document with those coming from a map.<p>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.<p>Example: | | replaceWith(options) | | | | sample(documents) | | Performs a pseudo-random sampling of the documents from the previous stage.<p>This stage will filter documents pseudo-randomly. The parameter specifies how number of documents to be returned.<p>Examples: | | sample(options) | | Performs a pseudo-random sampling of the documents from the previous stage.<p>This stage will filter documents pseudo-randomly. The 'options' parameter specifies how sampling will be performed. See SampleStageOptions for more information. | | search(options) | | | | select(selection, additionalSelections) | | Selects or creates a set of fields from the outputs of previous stages.<p>The selected fields are defined using Selectable expressions, which can be:<ul> <li><code>string</code> : Name of an existing field</li> <li>Field<!-- -->: References an existing field.</li> <li>AliasedExpression<!-- -->: Represents the result of a function with an assigned alias name using Expression.as()</li> </ul><p>If no selections are provided, the output of this stage is empty. Use Pipeline.addFields() instead if only additions are desired.<p>Example: | | select(options) | | Selects or creates a set of fields from the outputs of previous stages.<p>The selected fields are defined using Selectable expressions, which can be:<ul> <li><code>string</code>: Name of an existing field</li> <li>Field<!-- -->: References an existing field.</li> <li>AliasedExpression<!-- -->: Represents the result of a function with an assigned alias name using Expression.as()</li> </ul><p>If no selections are provided, the output of this stage is empty. Use Pipeline.addFields() instead if only additions are desired.<p>Example: | | sort(ordering, additionalOrderings) | | Sorts the documents from previous stages based on one or more Ordering criteria.<p>This stage allows you to order the results of your pipeline. You can specify multiple Ordering 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.<p>Example: | | sort(options) | | | | toArrayExpression() | | | | toScalarExpression() | | | | union(other) | | Performs union of all documents from two pipelines, including duplicates.<p>This stage will pass through documents from previous stage, and also pass through documents from previous stage of the <code>other</code> Pipeline given in parameter. The order of documents emitted from this stage is undefined.<p>Example: | | union(options) | | | | unnest(selectable, indexField) | | 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 <code>selectable</code> parameter, will emit an augmented document for each input array element. The input array element will augment the previous stage document by setting the <code>alias</code> field with the array element value.<!-- -->When <code>selectable</code> 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 <code>alias</code> field absent.<!-- -->No documents are emitted when <code>selectable</code> evaluates to an empty array.<!-- -->Example: | | unnest(options) | | | | where(condition) | | Filters the documents from previous stages to only include those matching the specified BooleanExpression<!-- -->.<p>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<!-- -->, typically including but not limited to:<ul> <li>field comparators: Expression.equal()<!-- -->, Expression.lessThan()<!-- -->, Expression.greaterThan()<!-- -->, etc.</li> <li>logical operators: , , , etc.</li> <li>advanced functions: Expression.regexMatch()<!-- -->, Expression.arrayContains()<!-- -->, etc.</li> </ul><p>Example: | | where(options) | | Filters the documents from previous stages to only include those matching the specified BooleanExpression<!-- -->.<p>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<!-- -->, typically including but not limited to:<ul> <li>field comparators: , (less than), Expression.greaterThan()<!-- -->, etc.</li> <li>logical operators: , , , etc.</li> <li>advanced functions: Expression.regexMatch()<!-- -->, Expression.arrayContains()<!-- -->, etc.</li> </ul><p>Example: |

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<!-- -->s, which can be:

Example:

<b>Signature:</b>

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

Parameters

ParameterTypeDescription
fieldSelectableThe first field to add to the documents, specified as a Selectable<!-- -->.
additionalFieldsSelectable<!-- -->[]Optional additional fields to add to the documents, specified as Selectable<!-- -->s.

<b>Returns:</b>

Pipeline

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()

<b>Signature:</b>

typescript
addFields(options: AddFieldsStageOptions): Pipeline;

Parameters

ParameterTypeDescription
optionsAddFieldsStageOptions

<b>Returns:</b>

Pipeline

Pipeline.aggregate()

Performs aggregation operations on the documents from previous stages.

<p>This stage allows you to calculate aggregate values over a set of documents. You define the aggregations to perform using [AliasedAggregate](./firestore_pipelines.aliasedaggregate.md#aliasedaggregate_class) expressions which are typically results of calling [Expression.as()](./firestore_pipelines.expression.md#expressionas) on [AggregateFunction](./firestore_pipelines.aggregatefunction.md#aggregatefunction_class) instances. <p>Example:

<b>Signature:</b>

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

Parameters

ParameterTypeDescription
accumulatorAliasedAggregateThe first AliasedAggregate<!-- -->, wrapping an AggregateFunction and providing a name for the accumulated results.
additionalAccumulatorsAliasedAggregate<!-- -->[]Optional additional AliasedAggregate<!-- -->, each wrapping an AggregateFunction and providing a name for the accumulated results.

<b>Returns:</b>

Pipeline

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.

<p>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: <ul> <li>\*\*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.</li> <li>\*\*Accumulators:\*\* One or more accumulation operations to perform within each group. These are defined using [AliasedAggregate](./firestore_pipelines.aliasedaggregate.md#aliasedaggregate_class) expressions, which are typically created by calling [Expression.as()](./firestore_pipelines.expression.md#expressionas) on [AggregateFunction](./firestore_pipelines.aggregatefunction.md#aggregatefunction_class) instances. Each aggregation calculates a value (e.g., sum, average, count) based on the documents within its group.</li> </ul> <p>Example:

<b>Signature:</b>

typescript
aggregate(options: AggregateStageOptions): Pipeline;

Parameters

ParameterTypeDescription
optionsAggregateStageOptionsAn object that specifies required and optional parameters for the stage.

<b>Returns:</b>

Pipeline

A new Pipeline 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()

<b>Signature:</b>

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

Parameters

ParameterTypeDescription
aliasedExpressionAliasedExpression
additionalExpressionsAliasedExpression<!-- -->[]

<b>Returns:</b>

Pipeline

Pipeline.define()

<b>Signature:</b>

typescript
define(options: DefineStageOptions): Pipeline;

Parameters

ParameterTypeDescription
optionsDefineStageOptions

<b>Returns:</b>

Pipeline

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 values (Field<!-- -->, AliasedExpression<!-- -->, etc).

The parameters to this stage are defined using Selectable expressions or strings:

  • string<!-- -->: Name of an existing field - Field<!-- -->: References an existing document field. - AliasedExpression<!-- -->: Represents the result of a function with an assigned alias name using Expression.as()<!-- -->.

Example:

<b>Signature:</b>

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

Parameters

ParameterTypeDescription
groupstring | SelectableThe Selectable expression or field name to consider when determining distinct value combinations.
additionalGroupsArray<string | Selectable<!-- -->>Optional additional Selectable expressions to consider when determining distinct value combinations or strings representing field names.

<b>Returns:</b>

Pipeline

A new Pipeline 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()

<b>Signature:</b>

typescript
distinct(options: DistinctStageOptions): Pipeline;

Parameters

ParameterTypeDescription
optionsDistinctStageOptions

<b>Returns:</b>

Pipeline

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<!-- -->.

<p>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
});

<b>Signature:</b>

typescript
findNearest(options: FindNearestStageOptions): Pipeline;

Parameters

ParameterTypeDescription
optionsFindNearestStageOptionsAn object that specifies required and optional parameters for the stage.

<b>Returns:</b>

Pipeline

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

Pipeline.limit()

Limits the maximum number of documents returned by previous stages to limit<!-- -->.

<p>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: <ul> <li>\*\*Pagination:\*\* In combination with to retrieve specific pages of results.</li> <li>\*\*Limiting Data Retrieval:\*\* To prevent excessive data transfer and improve performance, especially when dealing with large collections.</li> </ul> <p>Example:

<b>Signature:</b>

typescript
limit(limit: number): Pipeline;

Parameters

ParameterTypeDescription
limitnumberThe maximum number of documents to return.

<b>Returns:</b>

Pipeline

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()

<b>Signature:</b>

typescript
limit(options: LimitStageOptions): Pipeline;

Parameters

ParameterTypeDescription
optionsLimitStageOptions

<b>Returns:</b>

Pipeline

Pipeline.offset()

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

<p>This stage is useful for implementing pagination in your pipelines, allowing you to retrieve results in chunks. It is typically used in conjunction with to control the size of each page. <p>Example:

<b>Signature:</b>

typescript
offset(offset: number): Pipeline;

Parameters

ParameterTypeDescription
offsetnumberThe number of documents to skip.

<b>Returns:</b>

Pipeline

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()

<b>Signature:</b>

typescript
offset(options: OffsetStageOptions): Pipeline;

Parameters

ParameterTypeDescription
optionsOffsetStageOptions

<b>Returns:</b>

Pipeline

Pipeline.rawStage()

Adds a raw stage to the pipeline.

<p>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. <p>Example (Assuming there is no 'where' stage available in SDK):

<b>Signature:</b>

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

Parameters

ParameterTypeDescription
namestringThe unique name of the raw stage to add.
paramsunknown[]A list of parameters to configure the raw stage's behavior.
options{ [key: string]: Expression | unknown; }An object of key value pairs that specifies optional parameters for the stage.

<b>Returns:</b>

Pipeline

A new Pipeline 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.

Example:

<b>Signature:</b>

typescript
removeFields(fieldValue: Field | string, ...additionalFields: Array<Field | string>): Pipeline;

Parameters

ParameterTypeDescription
fieldValueField | stringThe first field to remove.
additionalFieldsArray<Field | string>Optional additional fields to remove.

<b>Returns:</b>

Pipeline

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()

<b>Signature:</b>

typescript
removeFields(options: RemoveFieldsStageOptions): Pipeline;

Parameters

ParameterTypeDescription
optionsRemoveFieldsStageOptions

<b>Returns:</b>

Pipeline

Pipeline.replaceWith()

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

<p>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. <p>Example:

<b>Signature:</b>

typescript
replaceWith(fieldName: string): Pipeline;

Parameters

ParameterTypeDescription
fieldNamestringThe Field field containing the nested map.

<b>Returns:</b>

Pipeline

A new Pipeline 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.

<p>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. <p>Example:

<b>Signature:</b>

typescript
replaceWith(expr: Expression): Pipeline;

Parameters

ParameterTypeDescription
exprExpressionAn Expression that when returned evaluates to a map.

<b>Returns:</b>

Pipeline

A new Pipeline 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()

<b>Signature:</b>

typescript
replaceWith(options: ReplaceWithStageOptions): Pipeline;

Parameters

ParameterTypeDescription
optionsReplaceWithStageOptions

<b>Returns:</b>

Pipeline

Pipeline.sample()

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

<p>This stage will filter documents pseudo-randomly. The parameter specifies how number of documents to be returned. <p>Examples:

<b>Signature:</b>

typescript
sample(documents: number): Pipeline;

Parameters

ParameterTypeDescription
documentsnumberThe number of documents to sample.

<b>Returns:</b>

Pipeline

A new Pipeline 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.

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

<b>Signature:</b>

typescript
sample(options: SampleStageOptions): Pipeline;

Parameters

ParameterTypeDescription
optionsSampleStageOptionsAn object that specifies required and optional parameters for the stage.

<b>Returns:</b>

Pipeline

A new Pipeline 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()

<b>Signature:</b>

typescript
search(options: SearchStageOptions): Pipeline;

Parameters

ParameterTypeDescription
optionsSearchStageOptions

<b>Returns:</b>

Pipeline

Pipeline.select()

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

<p>The selected fields are defined using [Selectable](./firestore_pipelines.selectable.md#selectable_interface) expressions, which can be: <ul> <li>`string` : Name of an existing field</li> <li>[Field](./firestore_pipelines.field.md#field_class)<!-- -->: References an existing field.</li> <li>[AliasedExpression](./firestore_pipelines.aliasedexpression.md#aliasedexpression_class)<!-- -->: Represents the result of a function with an assigned alias name using [Expression.as()](./firestore_pipelines.expression.md#expressionas)</li> </ul> <p>If no selections are provided, the output of this stage is empty. Use [Pipeline.addFields()](./firestore_pipelines.pipeline.md#pipelineaddfields) instead if only additions are desired. <p>Example:

<b>Signature:</b>

typescript
select(selection: Selectable | string, ...additionalSelections: Array<Selectable | string>): Pipeline;

Parameters

ParameterTypeDescription
selectionSelectable | stringThe first field to include in the output documents, specified as Selectable expression or string value representing the field name.
additionalSelectionsArray<Selectable | string>Optional additional fields to include in the output documents, specified as Selectable expressions or <code>string</code> values representing field names.

<b>Returns:</b>

Pipeline

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.

<p>The selected fields are defined using [Selectable](./firestore_pipelines.selectable.md#selectable_interface) expressions, which can be: <ul> <li>`string`<!-- -->: Name of an existing field</li> <li>[Field](./firestore_pipelines.field.md#field_class)<!-- -->: References an existing field.</li> <li>[AliasedExpression](./firestore_pipelines.aliasedexpression.md#aliasedexpression_class)<!-- -->: Represents the result of a function with an assigned alias name using [Expression.as()](./firestore_pipelines.expression.md#expressionas)</li> </ul> <p>If no selections are provided, the output of this stage is empty. Use [Pipeline.addFields()](./firestore_pipelines.pipeline.md#pipelineaddfields) instead if only additions are desired. <p>Example:

<b>Signature:</b>

typescript
select(options: SelectStageOptions): Pipeline;

Parameters

ParameterTypeDescription
optionsSelectStageOptionsAn object that specifies required and optional parameters for the stage.

<b>Returns:</b>

Pipeline

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 criteria.

<p>This stage allows you to order the results of your pipeline. You can specify multiple [Ordering](./firestore_pipelines.ordering.md#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. <p>Example:

<b>Signature:</b>

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

Parameters

ParameterTypeDescription
orderingOrderingThe first Ordering instance specifying the sorting criteria.
additionalOrderingsOrdering<!-- -->[]Optional additional Ordering instances specifying the additional sorting criteria.

<b>Returns:</b>

Pipeline

A new Pipeline 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()

<b>Signature:</b>

typescript
sort(options: SortStageOptions): Pipeline;

Parameters

ParameterTypeDescription
optionsSortStageOptions

<b>Returns:</b>

Pipeline

Pipeline.toArrayExpression()

<b>Signature:</b>

typescript
toArrayExpression(): Expression;

<b>Returns:</b>

Expression

Pipeline.toScalarExpression()

<b>Signature:</b>

typescript
toScalarExpression(): Expression;

<b>Returns:</b>

Expression

Pipeline.union()

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

<p>This stage will pass through documents from previous stage, and also pass through documents from previous stage of the `other` [Pipeline](./firestore_pipelines.pipeline.md#pipeline_class) given in parameter. The order of documents emitted from this stage is undefined. <p>Example:

<b>Signature:</b>

typescript
union(other: Pipeline): Pipeline;

Parameters

ParameterTypeDescription
otherPipelineThe other Pipeline that is part of union.

<b>Returns:</b>

Pipeline

A new Pipeline 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()

<b>Signature:</b>

typescript
union(options: UnionStageOptions): Pipeline;

Parameters

ParameterTypeDescription
optionsUnionStageOptions

<b>Returns:</b>

Pipeline

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.

Example:

<b>Signature:</b>

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

Parameters

ParameterTypeDescription
selectableSelectableA selectable expression defining the field to unnest and the alias to use for each un-nested element in the output documents.
indexFieldstringAn optional string value specifying the field path to write the offset (starting at zero) into the array the un-nested element is from

<b>Returns:</b>

Pipeline

A new Pipeline 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()

<b>Signature:</b>

typescript
unnest(options: UnnestStageOptions): Pipeline;

Parameters

ParameterTypeDescription
optionsUnnestStageOptions

<b>Returns:</b>

Pipeline

Pipeline.where()

Filters the documents from previous stages to only include those matching the specified BooleanExpression<!-- -->.

<p>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](./firestore_pipelines.booleanexpression.md#booleanexpression_class)<!-- -->, typically including but not limited to: <ul> <li>field comparators: [Expression.equal()](./firestore_pipelines.expression.md#expressionequal)<!-- -->, [Expression.lessThan()](./firestore_pipelines.expression.md#expressionlessthan)<!-- -->, [Expression.greaterThan()](./firestore_pipelines.expression.md#expressiongreaterthan)<!-- -->, etc.</li> <li>logical operators: , , , etc.</li> <li>advanced functions: [Expression.regexMatch()](./firestore_pipelines.expression.md#expressionregexmatch)<!-- -->, [Expression.arrayContains()](./firestore_pipelines.expression.md#expressionarraycontains)<!-- -->, etc.</li> </ul> <p>Example:

<b>Signature:</b>

typescript
where(condition: BooleanExpression): Pipeline;

Parameters

ParameterTypeDescription
conditionBooleanExpressionThe BooleanExpression to apply.

<b>Returns:</b>

Pipeline

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<!-- -->.

<p>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](./firestore_pipelines.booleanexpression.md#booleanexpression_class)<!-- -->, typically including but not limited to: <ul> <li>field comparators: , (less than), [Expression.greaterThan()](./firestore_pipelines.expression.md#expressiongreaterthan)<!-- -->, etc.</li> <li>logical operators: , , , etc.</li> <li>advanced functions: [Expression.regexMatch()](./firestore_pipelines.expression.md#expressionregexmatch)<!-- -->, [Expression.arrayContains()](./firestore_pipelines.expression.md#expressionarraycontains)<!-- -->, etc.</li> </ul> <p>Example:

<b>Signature:</b>

typescript
where(options: WhereStageOptions): Pipeline;

Parameters

ParameterTypeDescription
optionsWhereStageOptionsAn object that specifies required and optional parameters for the stage.

<b>Returns:</b>

Pipeline

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")
)
);