Pipeline

@Beta
public final classPipeline


APipeline is composed of a sequence of stages. Each stage processes the output from the previous one, and the final stage's output is the result of the pipeline's execution.

Example usage:

{@code Pipeline pipeline = firestore.pipeline().collection("books") .where(Field("rating").isGreaterThan(4.5)).sort(Field("rating").descending()) .limit(2); }

Note on Execution: The stages are conceptual. The Firestore backend may optimizeexecution (e.g., reordering or merging stages) as long as the final result remains the same.

Important Limitations:

  • Pipelines operate on arequest/response basisonly.
  • They donot utilize or update the local SDK cache.
  • They donotsupport realtime snapshot listeners.

Summary

Nested types

public final classPipeline.ExecuteOptions extendsAbstractOptions
public final classPipeline.Snapshot implementsIterable

ASnapshot contains the results of a pipeline execution.

Public methods

final @NonNullPipeline
addFields(@NonNullSelectable field, @NonNullSelectable additionalFields)

Adds new fields to outputs from previous stages.

final @NonNullPipeline

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

final @NonNullPipeline
aggregate(
    @NonNullAliasedAggregate accumulator,
    @NonNullAliasedAggregate additionalAccumulators
)

Performs aggregation operations on the documents from previous stages.

final @NonNullPipeline
aggregate(
    @NonNullAggregateStage aggregateStage,
    @NonNullAggregateOptions options
)

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

final @NonNullPipeline
distinct(@NonNullSelectable group, @NonNullObject additionalGroups)

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

final @NonNullPipeline
distinct(@NonNullString groupField, @NonNullObject additionalGroups)

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

final @NonNullTask<@NonNullPipeline.Snapshot>

Executes this pipeline and returns the results as aTask ofSnapshot.

final @NonNullTask<@NonNullPipeline.Snapshot>

Executes this pipeline and returns the results as aTask ofSnapshot.

final @NonNullPipeline
findNearest(
    @NonNullField vectorField,
    @NonNull double[] vectorValue,
    @NonNullFindNearestStage.DistanceMeasure distanceMeasure
)

Performs a vector similarity search, ordering the result set by most similar to least similar, and returning the full set in the order of similarity.

final @NonNullPipeline
findNearest(
    @NonNullString vectorField,
    @NonNull double[] vectorValue,
    @NonNullFindNearestStage.DistanceMeasure distanceMeasure
)

Performs a vector similarity search, ordering the result set by most similar to least similar, and returning the full set in the order of similarity.

final @NonNullPipeline
findNearest(
    @NonNullString vectorField,
    @NonNullExpression vectorValue,
    @NonNullFindNearestStage.DistanceMeasure distanceMeasure,
    @NonNullFindNearestOptions options
)

Performs a vector similarity search, ordering the result set by most similar to least similar, and returning the first N documents (specified byFindNearestOptions.withLimit) in the result set.

final @NonNullPipeline
limit(int limit)

Limits the maximum number of documents returned by previous stages tolimit.

final @NonNullPipeline
offset(int offset)

Skips the firstoffset number of documents from the results of previous stages.

final @NonNullPipeline

Adds a raw stage to the pipeline by specifying the stage name as an argument.

final @NonNullPipeline
removeFields(@NonNullField field, @NonNullField additionalFields)

Remove fields from outputs of previous stages.

final @NonNullPipeline
removeFields(@NonNullString field, @NonNullString additionalFields)

Remove fields from outputs of previous stages.

final @NonNullPipeline

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

final @NonNullPipeline

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

final @NonNullPipeline
sample(int documents)

Performs a pseudo-random sampling of the input documents.

final @NonNullPipeline

Performs a pseudo-random sampling of the input documents.

final @NonNullPipeline
select(@NonNullString fieldName, @NonNullObject additionalSelections)

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

final @NonNullPipeline
select(@NonNullSelectable selection, @NonNullObject additionalSelections)

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

final @NonNullPipeline
sort(@NonNullOrdering order, @NonNullOrdering additionalOrders)

Sorts the documents from previous stages based on one or moreOrdering criteria.

final @NonNullPipeline

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

final @NonNullPipeline
unnest(@NonNullSelectable arrayWithAlias)

Takes a specified array from the input documents and outputs a document for each element with the element stored in a field with name specified by the alias.

final @NonNullPipeline
unnest(@NonNullUnnestStage unnestStage)

Takes a specified array from the input documents and outputs a document for each element with the element stored in a field with name specified by the alias.

final @NonNullPipeline
unnest(@NonNullString arrayField, @NonNullString alias)

Takes a specified array from the input documents and outputs a document for each element with the element stored in a field with name specified by the alias.

final @NonNullPipeline
unnest(@NonNullSelectable arrayWithAlias, @NonNullUnnestOptions options)

Takes a specified array from the input documents and outputs a document for each element with the element stored in a field with name specified by the alias.

final @NonNullPipeline

Filters the documents from previous stages to only include those matching the specifiedBooleanExpression.

Public methods

addFields

public final @NonNullPipeline addFields(@NonNullSelectable field, @NonNullSelectable 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.

The added fields are defined usingSelectables, which can be:

  • Field: References an existing document field.

  • AliasedExpression: Represents the result of a expression with an assigned alias name using Expr.alias

Example:

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

The first field to add to the documents, specified as aSelectable.

@NonNullSelectable additionalFields

The fields to add to the documents, specified asSelectables.

Returns
@NonNullPipeline

A newPipeline object with this stage appended to the stage list.

aggregate

public final @NonNullPipeline aggregate(@NonNullAggregateStage aggregateStage)

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 Expressions: 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.

  • AggregateFunctions: One or more accumulation operations to perform within each group. These are defined usingAliasedAggregate expressions, which are typically created by callingAggregateFunction.alias onAggregateFunction instances. Each aggregation calculates a value (e.g., sum, average, count) based on the documents within its group.

Example:

// Calculate the average rating for each genre.
firestore.pipeline().collection("books")
.aggregate(
Aggregate
.withAccumulators(average("rating").as("avg_rating"))
.withGroups("genre"));
Parameters
@NonNullAggregateStage aggregateStage

AnAggregateStage object that specifies the grouping fields (if any) and the aggregation operations to perform.

Returns
@NonNullPipeline

A newPipeline object with this stage appended to the stage list.

aggregate

public final @NonNullPipeline aggregate(
    @NonNullAliasedAggregate accumulator,
    @NonNullAliasedAggregate additionalAccumulators
)

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 usingAliasedAggregate expressions which are typically results of callingAggregateFunction.alias onAggregateFunction instances.

Example:

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

The firstAliasedAggregate expression, wrapping anAggregateFunction with an alias for the accumulated results.

@NonNullAliasedAggregate additionalAccumulators

TheAliasedAggregate expressions, each wrapping anAggregateFunction with an alias for the accumulated results.

Returns
@NonNullPipeline

A newPipeline object with this stage appended to the stage list.

aggregate

public final @NonNullPipeline aggregate(
    @NonNullAggregateStage aggregateStage,
    @NonNullAggregateOptions options
)

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 Expressions: 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.

  • AggregateFunctions: One or more accumulation operations to perform within each group. These are defined usingAliasedAggregate expressions, which are typically created by callingAggregateFunction.alias onAggregateFunction instances. Each aggregation calculates a value (e.g., sum, average, count) based on the documents within its group.

Parameters
@NonNullAggregateStage aggregateStage

AnAggregateStage object that specifies the grouping fields (if any) and the aggregation operations to perform.

@NonNullAggregateOptions options

TheAggregateOptions to use when performing the aggregation.

Returns
@NonNullPipeline

A newPipeline object with this stage appended to the stage list.

distinct

public final @NonNullPipeline distinct(@NonNullSelectable group, @NonNullObject 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 Expr valuesField,FunctionExpression, etc).

The parameters to this stage are defined usingSelectable 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 Expr.alias

Example:

// Get a list of unique author names in uppercase and genre combinations.
firestore.pipeline().collection("books")
.distinct(toUppercase(field("author")).as("authorName"), field("genre"))
.select("authorName");
Parameters
@NonNullSelectable group

TheSelectable expression to consider when determining distinct value combinations.

@NonNullObject additionalGroups

TheSelectable expressions to consider when determining distinct value combinations orStrings representing field names.

Returns
@NonNullPipeline

A newPipeline object with this stage appended to the stage list.

distinct

public final @NonNullPipeline distinct(@NonNullString groupField, @NonNullObject 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 Expr values (Field,FunctionExpression, etc).

The parameters to this stage are defined usingSelectable 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 Expr.alias

Example:

// Get a list of unique genres.
firestore.pipeline().collection("books")
.distinct("genre");
Parameters
@NonNullString groupField

TheString representing field name.

@NonNullObject additionalGroups

TheSelectable expressions to consider when determining distinct value combinations orStrings representing field names.

Returns
@NonNullPipeline

A newPipeline object with this stage appended to the stage list.

execute

public final @NonNullTask<@NonNullPipeline.Snapshotexecute()

Executes this pipeline and returns the results as aTask ofSnapshot.

Returns
@NonNullTask<@NonNullPipeline.Snapshot>

ATask that will be resolved with the results of the pipeline.

execute

public final @NonNullTask<@NonNullPipeline.Snapshotexecute(@NonNullPipeline.ExecuteOptions options)

Executes this pipeline and returns the results as aTask ofSnapshot.

Parameters
@NonNullPipeline.ExecuteOptions options

TheExecuteOptions to use to instruct Firestore backend execution.

Returns
@NonNullTask<@NonNullPipeline.Snapshot>

ATask that will be resolved with the results of the pipeline.

findNearest

public final @NonNullPipeline findNearest(
    @NonNullField vectorField,
    @NonNull double[] vectorValue,
    @NonNullFindNearestStage.DistanceMeasure distanceMeasure
)

Performs a vector similarity search, ordering the result set by most similar to least similar, and returning the full set in the order of similarity.

Parameters
@NonNullField vectorField

AField that contains vector to search on.

@NonNull double[] vectorValue

TheDoubleArray that is used to measure the distance fromvectorField values in the documents.

@NonNullFindNearestStage.DistanceMeasure distanceMeasure

specifies what type of distance is calculated. when performing the search.

Returns
@NonNullPipeline

A newPipeline object with this stage appended to the stage list.

findNearest

public final @NonNullPipeline findNearest(
    @NonNullString vectorField,
    @NonNull double[] vectorValue,
    @NonNullFindNearestStage.DistanceMeasure distanceMeasure
)

Performs a vector similarity search, ordering the result set by most similar to least similar, and returning the full set in the order of similarity.

Parameters
@NonNullString vectorField

AString specifying the vector field to search on.

@NonNull double[] vectorValue

TheDoubleArray that is used to measure the distance fromvectorField values in the documents.

@NonNullFindNearestStage.DistanceMeasure distanceMeasure

specifies what type of distance is calculated when performing the search.

Returns
@NonNullPipeline

A newPipeline object with this stage appended to the stage list.

findNearest

public final @NonNullPipeline findNearest(
    @NonNullString vectorField,
    @NonNullExpression vectorValue,
    @NonNullFindNearestStage.DistanceMeasure distanceMeasure,
    @NonNullFindNearestOptions options
)

Performs a vector similarity search, ordering the result set by most similar to least similar, and returning the first N documents (specified byFindNearestOptions.withLimit) in the result set.

Example:

// Find books with similar "topicVectors" to the given targetVector
firestore.pipeline().collection("books")
.findNearest("topicVectors", targetVector, FindNearest.DistanceMeasure.COSINE,
new FindNearestOptions()
.withLimit(10)
.withDistanceField("distance"));
Parameters
@NonNullString vectorField

A field name that contains vector to search on.

@NonNullExpression vectorValue

TheExpression that should evaluate to a vector used to measure the distance fromvectorField values in the documents.

@NonNullFindNearestStage.DistanceMeasure distanceMeasure

specifies what type of distance is calculated when performing the search.

@NonNullFindNearestOptions options

TheFindNearestOptions to use when performing the search.

Returns
@NonNullPipeline

A newPipeline object with this stage appended to the stage list.

limit

public final @NonNullPipeline limit(int limit)

Limits the maximum number of documents returned by previous stages tolimit.

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 withoffset to retrieve specific pages of results.

  • Limiting Data Retrieval: To prevent excessive data transfer and improve performance, especially when dealing with large collections.

Example:

// Limit the results to the top 10 highest-rated books
firestore.pipeline().collection("books")
.sort(field("rating").descending())
.limit(10);
Parameters
int limit

The maximum number of documents to return.

Returns
@NonNullPipeline

A newPipeline object with this stage appended to the stage list.

offset

public final @NonNullPipeline offset(int offset)

Skips the firstoffset 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 withlimit to control the size of each page.

Example:

// 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
Parameters
int offset

The number of documents to skip.

Returns
@NonNullPipeline

A newPipeline object with this stage appended to the stage list.

rawStage

public final @NonNullPipeline rawStage(@NonNullRawStage rawStage)

Adds a raw stage to the pipeline by specifying the stage name as an argument. This does not offer any type safety on the stage params and requires the caller to know the order (and optionally names) of parameters accepted by the stage.

This method provides a way to call stages that are supported by the Firestore backend but that are not implemented in the SDK version being used.

Parameters
@NonNullRawStage rawStage

ARawStage object that specifies stage name and parameters.

Returns
@NonNullPipeline

A newPipeline object with this stage appended to the stage list.

removeFields

public final @NonNullPipeline removeFields(@NonNullField field, @NonNullField additionalFields)

Remove fields from outputs of previous stages.

Example:

firestore.pipeline().collection("books")
.removeFields(
field("rating"), field("cost")
);
Parameters
@NonNullField field

The firstField to remove.

@NonNullField additionalFields

Optional additionalFields to remove.

Returns
@NonNullPipeline

A newPipeline object with this stage appended to the stage list.

removeFields

public final @NonNullPipeline removeFields(@NonNullString field, @NonNullString additionalFields)

Remove fields from outputs of previous stages.

Example:

firestore.pipeline().collection("books")
.removeFields(
"rating", "cost"
);
Parameters
@NonNullString field

The firstString name of field to remove.

@NonNullString additionalFields

Optional additionalString name of fields to remove.

Returns
@NonNullPipeline

A newPipeline object with this stage appended to the stage list.

replaceWith

public final @NonNullPipeline replaceWith(@NonNullString field)

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.

Example:

// 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"
// }
Parameters
@NonNullString field

TheString specifying the field name containing the nested map.

Returns
@NonNullPipeline

A newPipeline object with this stage appended to the stage list.

replaceWith

public final @NonNullPipeline replaceWith(@NonNullExpression mapValue)

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.

Example:

// Input.
// {
// "name": "John Doe Jr.",
// "parents": {
// "father": "John Doe Sr.",
// "mother": "Jane Doe"
// }

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

// Output
// {
// "father": "John Doe Sr.",
// "mother": "Jane Doe"
// }
Parameters
@NonNullExpression mapValue

TheExpression orField containing the nested map.

Returns
@NonNullPipeline

A newPipeline object with this stage appended to the stage list.

sample

public final @NonNullPipeline sample(int documents)

Performs a pseudo-random sampling of the input documents.

Thedocuments parameter represents the target number of documents to produce and must be a non-negative integer value. If the previous stage produces less than size documents, the entire previous results are returned. If the previous stage produces more than size, this outputs a sample of exactly size entries where any sample is equally likely.

Example:

// Sample 10 books, if available.
firestore.pipeline().collection("books")
.sample(10);
Parameters
int documents

The number of documents to emit.

Returns
@NonNullPipeline

A newPipeline object with this stage appended to the stage list.

sample

public final @NonNullPipeline sample(@NonNullSampleStage sample)

Performs a pseudo-random sampling of the input documents.

Examples:

// Sample 10 books, if available.
firestore.pipeline().collection("books")
.sample(Sample.withDocLimit(10));

// Sample 50% of books.
firestore.pipeline().collection("books")
.sample(Sample.withPercentage(0.5));
Parameters
@NonNullSampleStage sample

AnSampleStage object that specifies how sampling is performed.

Returns
@NonNullPipeline

A newPipeline object with this stage appended to the stage list.

select

public final @NonNullPipeline select(@NonNullString fieldName, @NonNullObject additionalSelections)

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

The selected fields are defined usingSelectable expressions, which can be:

  • String: Name of an existing field

  • Field: Reference to an existing field.

  • AliasedExpression: Represents the result of a expression with an assigned alias name using Expr.alias

If no selections are provided, the output of this stage is empty. UsePipeline.addFields instead if only additions are desired.

Example:

firestore.collection("books")
.select("name","address");

// The above is a shorthand of this:
firestore.pipeline().collection("books")
.select(field("name"), field("address"));
Parameters
@NonNullString fieldName

The first field to include in the output documents, specified as a string value representing a field names.

@NonNullObject additionalSelections

Optional additional fields to include in the output documents, specified asSelectable expressions or string values representing field names.

Returns
@NonNullPipeline

A newPipeline object with this stage appended to the stage list.

select

public final @NonNullPipeline select(@NonNullSelectable selection, @NonNullObject additionalSelections)

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

The selected fields are defined usingSelectable expressions or strings, which can be:

  • String: Name of an existing field

  • Field: Reference to an existing field.

  • AliasedExpression: Represents the result of a expression with an assigned alias name using Expr.alias

If no selections are provided, the output of this stage is empty. UsePipeline.addFields instead if only additions are desired.

Example:

firestore.pipeline().collection("books")
.select(
field("name"),
field("address").toUppercase().as("upperAddress"),
);
Parameters
@NonNullSelectable selection

The first field to include in the output documents, specified as aSelectable expression.

@NonNullObject additionalSelections

Optional additional fields to include in the output documents, specified asSelectable expressions or string values representing field names.

Returns
@NonNullPipeline

A newPipeline object with this stage appended to the stage list.

sort

public final @NonNullPipeline sort(@NonNullOrdering order, @NonNullOrdering additionalOrders)

Sorts the documents from previous stages based on one or moreOrdering criteria.

This stage allows you to order the results of your pipeline. You can specify multipleOrdering 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.

Example:

// 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(
Ordering.of("rating").descending(),
Ordering.of("title") // Ascending order is the default
);
Parameters
@NonNullOrdering order

The firstOrdering instance specifying the sorting criteria.

@NonNullOrdering additionalOrders

Optional additionalOrdering instances specifying the sorting criteria.

Returns
@NonNullPipeline

A newPipeline object with this stage appended to the stage list.

union

public final @NonNullPipeline union(@NonNullPipeline other)

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 theother Pipeline given in parameter. The order of documents emitted from this stage is undefined.

Example:

// Emit documents from books collection and magazines collection.
firestore.pipeline().collection("books")
.union(firestore.pipeline().collection("magazines"));
Parameters
@NonNullPipeline other

The otherPipeline that is part of union.

Returns
@NonNullPipeline

A newPipeline object with this stage appended to the stage list.

unnest

public final @NonNullPipeline unnest(@NonNullSelectable arrayWithAlias)

Takes a specified array from the input documents and outputs a document for each element with the element stored in a field with name specified by the alias.

For each document emitted by the prior stage, this stage will emit zero or more augmented documents. The input array is found in parameterarrayWithAlias, which can be an Expr with an alias specified via Expr.alias, or aField that can also have alias specified. For each element of the input array, an augmented document will be produced. The element of input array will be stored in a field with name specified by the alias of thearrayWithAlias parameter. If thearrayWithAlias is aField with no alias, then the original array field will be replaced with the individual element.

Parameters
@NonNullSelectable arrayWithAlias

The input array with field alias to store output element of array.

Returns
@NonNullPipeline

A newPipeline object with this stage appended to the stage list.

unnest

public final @NonNullPipeline unnest(@NonNullUnnestStage unnestStage)

Takes a specified array from the input documents and outputs a document for each element with the element stored in a field with name specified by the alias.

For each document emitted by the prior stage, this stage will emit zero or more augmented documents. The input array specified in theunnestStage parameter will for each element of the input array produce an augmented document. The element of the input array will be stored in a field with a name specified by theunnestStage parameter.

Optionally, an index field can also be added to emitted documents. SeeUnnestStage for further information.

Parameters
@NonNullUnnestStage unnestStage

AnUnnestStage object that specifies the search parameters.

Returns
@NonNullPipeline

A newPipeline object with this stage appended to the stage list.

unnest

public final @NonNullPipeline unnest(@NonNullString arrayField, @NonNullString alias)

Takes a specified array from the input documents and outputs a document for each element with the element stored in a field with name specified by the alias.

For each document emitted by the prior stage, this stage will emit zero or more augmented documents. The input array found in the previous stage document field specified by thearrayField parameter, will for each element of the input array produce an augmented document. The element of the input array will be stored in a field with name specified byalias parameter on the augmented document.

Example:

// 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("tags", "tag");

// Output:
// { "title": "The Hitchhiker's Guide to the Galaxy", "tag": "comedy", ... }
// { "title": "The Hitchhiker's Guide to the Galaxy", "tag": "space", ... }
// { "title": "The Hitchhiker's Guide to the Galaxy", "tag": "adventure", ... }
Parameters
@NonNullString arrayField

The name of the field containing the array.

@NonNullString alias

The name of field to store emitted element of array.

Returns
@NonNullPipeline

A newPipeline object with this stage appended to the stage list.

unnest

public final @NonNullPipeline unnest(@NonNullSelectable arrayWithAlias, @NonNullUnnestOptions options)

Takes a specified array from the input documents and outputs a document for each element with the element stored in a field with name specified by the alias.

For each document emitted by the prior stage, this stage will emit zero or more augmented documents. The input array is found in parameterarrayWithAlias, which can be an Expr with an alias specified via Expr.alias, or aField that can also have alias specified. For each element of the input array, an augmented document will be produced. The element of input array will be stored in a field with name specified by the alias of thearrayWithAlias parameter. If thearrayWithAlias is aField with no alias, then the original array field will be replaced with the individual element.

Example:

// 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("tags", "tag", new UnnestOptions().withIndexField("tagIndex"));

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

The input array with field alias to store output element of array.

@NonNullUnnestOptions options

TheUnnestOptions to use when performing the unnest.

Returns
@NonNullPipeline

A newPipeline object with this stage appended to the stage list.

where

public final @NonNullPipeline where(@NonNullBooleanExpression condition)

Filters the documents from previous stages to only include those matching the specifiedBooleanExpression.

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 ofBooleanExpression, typically including but not limited to:

  • field comparators: Expr.equal, Expr.lessThan, Expr.greaterThan, etc.

  • logical operators: Expr.and, Expr.or, Expr.not, etc.

  • advanced functions: Expr.regexMatch, Expr.arrayContains, etc.

Example:

firestore.pipeline().collection("books")
.where(
and(
gt("rating", 4.0), // Filter for ratings greater than 4.0
field("genre").equal("Science Fiction") // Equivalent to equal("genre", "Science Fiction")
)
);
Parameters
@NonNullBooleanExpression condition

TheBooleanExpression to apply.

Returns
@NonNullPipeline

A newPipeline object with this stage appended to the stage list.

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2026-01-15 UTC.