Expression

Expression

Represents an expression that can be evaluated to a value within the execution of a Pipeline.

Expressions are the building blocks for creating complex queries and transformations in Firestore pipelines. They can represent:

  • Field references: Access values from document fields.
  • Literals: Represent constant values (strings, numbers, booleans).
  • Function calls: Apply functions to one or more expressions.

The Expression class provides a fluent API for building expressions. You can chain together method calls to create complex expressions.

Constructor

new Expression()

Methods

abs()

Creates an expression that computes the absolute value of a numeric value.

Returns:
Type Description

A new Expr representing the absolute value of the numeric value.

Example
```typescript
// Compute the absolute value of the 'price' field.
field("price").abs();
```

add(second, …others)

Creates an expression that adds this expression to another expression.

Parameters:
Name Type Attributes Description
second

The expression or literal to add to this expression.

others <repeatable>

Optional additional expressions or literals to add to this expression.

Returns:
Type Description

A new Expression representing the addition operation.

Example
```typescript
// Add the value of the 'quantity' field and the 'reserve' field.
field("quantity").add(field("reserve"));
```

arrayAgg()

Creates an aggregation that collects all values of an expression across multiple stage inputs into an array.

Returns:
Type Description

A new AggregateFunction representing the 'array_agg' aggregation.

Example
```typescript
// Collect all tags from books into an array
field("tags").arrayAgg().as("allTags");
```

arrayAggDistinct()

Creates an aggregation that collects all distinct values of an expression across multiple stage inputs into an array.

Returns:
Type Description

A new AggregateFunction representing the 'array_agg_distinct' aggregation.

Example
```typescript
// Collect all distinct tags from books into an array
field("tags").arrayAggDistinct().as("allDistinctTags");
```

arrayConcat(secondArray, …otherArrays)

Creates an expression that concatenates an array expression with one or more other arrays.

Parameters:
Name Type Attributes Description
secondArray

Second array expression or array literal to concatenate.

otherArrays <repeatable>

Optional additional array expressions or array literals to concatenate.

Returns:
Type Description

A new Expr representing the concatenated array.

Example
```typescript
// Combine the 'items' array with another array field.
field("items").arrayConcat(field("otherItems"));
```

arrayFilter(alias, filter)

Creates an expression that filters an array using a provided alias and predicate expression.

Parameters:
Name Type Description
alias

The variable name to use for each element.

filter

The predicate boolean expression to evaluate for each element.

Returns:
Type Description

A new Expression representing the filtered array.

Example
```typescript
// Filter "scores" to include only values greater than 50
field("scores").arrayFilter("score", greaterThan(variable("score"), 50));
```

arrayFirst()

Returns the first element of the array.

Returns:
Type Description

A new Expression representing the first element.

Example
```typescript
// Get the first element of the 'myArray' field.
field("myArray").arrayFirst();
```

arrayLast()

Returns the last element of the array.

Returns:
Type Description

A new Expression representing the last element.

Example
```typescript
// Get the last element of the 'myArray' field.
field("myArray").arrayLast();
```

arrayLength()

Creates an expression that calculates the length of an array.

Returns:
Type Description

A new Expression representing the length of the array.

Example
```typescript
// Get the number of items in the 'cart' array
field("cart").arrayLength();
```

arrayMaximum()

Returns the maximum value in the array.

Returns:
Type Description

A new Expression representing the maximum value.

Example
```typescript
// Get the maximum value of the 'myArray' field.
field("myArray").arrayMaximum();
```

arrayMinimum()

Returns the minimum value in the array.

Returns:
Type Description

A new Expression representing the minimum value.

Example
```typescript
// Get the minimum value of the 'myArray' field.
field("myArray").arrayMinimum();
```

arrayReverse()

Creates an expression that reverses an array.

Returns:
Type Description

A new Expression representing the reversed array.

Example
```typescript
// Reverse the value of the 'myArray' field.
field("myArray").arrayReverse();
```

arraySlice(offset, length)

Creates an expression that returns a slice of an array from offset with length elements.

Parameters:
Name Type Description
offset

The starting offset.

length

The optional length of the slice.

Returns:
Type Description

A new Expression representing the sliced array.

Example
```typescript
// Get 5 elements from the 'items' array starting from index 2
field("items").arraySlice(2, 5);

// Get n number of elements from the 'items' array starting from index 2
field("items").arraySlice(2, field("count"));
```

arraySum()

Creates an expression that computes the sum of the elements in an array.

// Compute the sum of the elements in the 'scores' field.
field("scores").arraySum();
Returns:
Type Description

A new Expr representing the sum of the elements in the array.

arrayTransform(elementAlias, transform)

Creates an expression that applies a provided transformation to each element in an array.

Parameters:
Name Type Description
elementAlias

The variable name to use for each element.

transform

The lambda expression used to transform the elements.

Returns:
Type Description

A new Expression representing the arrayTransform operation.

Example
```typescript
// Transform the 'scores' array by multiplying each score by 10
field("scores").arrayTransform("score", multiply(variable("score"), 10));
```

arrayTransformWithIndex(elementAlias, indexAlias, transform)

Creates an expression that applies a provided transformation to each element in an array, providing the element's index to the transformation expression.

Parameters:
Name Type Description
elementAlias

The variable name to use for each element.

indexAlias

The variable name to use for the current index.

transform

The lambda expression used to transform the elements.

Returns:
Type Description

A new Expression representing the arrayTransformWithIndex operation.

Example
```typescript
// Transform the 'scores' array by adding the index to each score
field("scores").arrayTransformWithIndex("score", "i", add(variable("score"), variable("i")));
```

as(name)

Assigns an alias to this expression.

Aliases are useful for renaming fields in the output of a stage or for giving meaningful names to calculated values.

// Calculate the total price and assign it the alias "totalPrice" and add it to the output.
firestore.pipeline().collection("items")
  .addFields(field("price").multiply(field("quantity")).as("totalPrice"));
Parameters:
Name Type Description
name

The alias to assign to this expression.

Returns:
Type Description

A new AliasedExpression that wraps this expression and associates it with the provided alias.

asBoolean()

Wraps the expression in a [BooleanExpression].

Returns:
Type Description

A BooleanExpression representing the same expression.

ascending()

Creates an Ordering that sorts documents in ascending order based on this expression.

// Sort documents by the 'name' field in ascending order
pipeline().collection("users")
  .sort(field("name").ascending());
Returns:
Type Description

A new Ordering for ascending sorting.

average()

Creates an aggregation that calculates the average (mean) of a numeric field across multiple stage inputs.

Returns:
Type Description

A new AggregateFunction representing the 'average' aggregation.

Example
```typescript
// Calculate the average age of users
field("age").average().as("averageAge");
```

byteLength()

Creates an expression that calculates the length of this string expression in bytes.

Returns:
Type Description

A new Expression representing the length of the string in bytes.

Example
```typescript
// Calculate the length of the 'myString' field in bytes.
field("myString").byteLength();
```

ceil()

Creates an expression that computes the ceiling of a numeric value.

Returns:
Type Description

A new Expression representing the ceiling of the numeric value.

Example
```typescript
// Compute the ceiling of the 'price' field.
field("price").ceil();
```

charLength()

Creates an expression that calculates the character length of a string in UTF-8.

Returns:
Type Description

A new Expression representing the length of the string.

Example
```typescript
// Get the character length of the 'name' field in its UTF-8 form.
field("name").charLength();
```

coalesce(replacement, …others)

Creates an expression that returns the first non-null, non-absent argument, without evaluating the rest of the arguments. When all arguments are null or absent, returns the last argument.

Parameters:
Name Type Attributes Description
replacement

The value to use if this expression evaluates to null.

others <repeatable>

Optional additional values to check if previous values are null.

Returns:
Type Description

A new [Expression] representing the coalesce operation.

Example
```typescript
// Returns the value of the first non-null, non-absent field among 'preferredName', 'fullName',
// or the last argument if all previous fields are null.
field("preferredName").coalesce(field("fullName"), "Anonymous");
```

collectionId()

Creates an expression that returns the collection ID from a path.

// Get the collection ID from a path.
field("__path__").collectionId();
Returns:
Type Description

A new Expression representing the collectionId operation.

concat(second, …others)

Creates an expression that concatenates expression results together.

Parameters:
Name Type Attributes Description
second

The additional expression or literal to concatenate.

others <repeatable>

Optional additional expressions or literals to concatenate.

Returns:
Type Description

A new Expr representing the concatenated value.

Example
```typescript
// Combine the 'firstName', ' ', and 'lastName' fields into a single value.
field("firstName").concat(constant(" "), field("lastName"));
```

count()

Creates an aggregation that counts the number of stage inputs with valid evaluations of the expression or field.

Returns:
Type Description

A new AggregateFunction representing the 'count' aggregation.

Example
```typescript
// Count the total number of products
field("productId").count().as("totalProducts");
```

countDistinct()

Creates an aggregation that counts the number of distinct values of the expression or field.

Returns:
Type Description

A new AggregateFunction representing the 'count_distinct' aggregation.

Example
```typescript
// Count the distinct number of products
field("productId").countDistinct().as("distinctProducts");
```

descending()

Creates an Ordering that sorts documents in descending order based on this expression.

// Sort documents by the 'createdAt' field in descending order
firestore.pipeline().collection("users")
  .sort(field("createdAt").descending());
Returns:
Type Description

A new Ordering for descending sorting.

documentId()

Creates an expression that returns the document ID from a path.

Returns:
Type Description

A new Expression representing the documentId operation.

Example
```typescript
// Get the document ID from a path.
field("__path__").documentId();
```

exists()

Creates an expression that checks if a field exists in the document.

Returns:
Type Description

A new Expression representing the 'exists' check.

Example
```typescript
// Check if the document has a field named "phoneNumber"
field("phoneNumber").exists();
```

exp()

Creates an expression that computes e to the power of this expression.

Returns:
Type Description

A new Expression representing the exp of the numeric value.

Example
```typescript
// Compute e to the power of the 'value' field.
field("value").exp();
```

first()

Creates an aggregation that finds the first value of an expression across multiple stage inputs.

Returns:
Type Description

A new AggregateFunction representing the 'first' aggregation.

Example
```typescript
// Find the first value of the 'rating' field
field("rating").first().as("firstRating");
```

floor()

Creates an expression that computes the floor of a numeric value.

Returns:
Type Description

A new Expression representing the floor of the numeric value.

Example
```typescript
// Compute the floor of the 'price' field.
field("price").floor();
```

getField(key)

Creates an expression that returns the value of a field from the document that results from the evaluation of this expression.

Parameters:
Name Type Description
key

The field to access in the document.

Returns:
Type Description

A new Expression representing the value of the field in the document.

Example
```typescript
// Get the value of the "city" field in the "address" document.
field("address").getField("city")
```

isAbsent()

Creates an expression that returns true if the result of this expression is absent. Otherwise, returns false even if the value is null.

// Check if the field `value` is absent.
field("value").isAbsent();
Returns:
Type Description

A new BooleanExpression representing the 'isAbsent' check.

isError()

Creates an expression that checks if a given expression produces an error.

Returns:
Type Description

A new BooleanExpression representing the 'isError' check.

Example
```typescript
// Check if the result of a calculation is an error
field("title").arrayContains(1).isError();
```

isType(type)

Creates an expression that checks if the result of this expression is of the given type.

Parameters:
Name Type Description
type

The type to check for.

Returns:
Type Description

A new BooleanExpression that evaluates to true if the expression's result is of the given type, false otherwise.

Example
```typescript
// Check if the 'price' field is specifically an integer (not just 'number')
field('price').isType('int64');
```

last()

Creates an aggregation that finds the last value of an expression across multiple stage inputs.

Returns:
Type Description

A new AggregateFunction representing the 'last' aggregation.

Example
```typescript
// Find the last value of the 'rating' field
field("rating").last().as("lastRating");
```

length()

Creates an expression that calculates the length of a string, array, map, vector, or bytes.

// Get the length of the 'name' field.
field("name").length();

// Get the number of items in the 'cart' array.
field("cart").length();
Returns:
Type Description

A new Expression representing the length of the string, array, map, vector, or bytes.

ln()

Creates an expression that computes the natural logarithm of a numeric value.

// Compute the natural logarithm of the 'value' field.
field("value").ln();
Returns:
Type Description

A new Expression representing the natural logarithm of the numeric value.

log10()

Creates an expression that computes the base-10 logarithm of a numeric value.

// Compute the base-10 logarithm of the 'value' field.
field("value").log10();
Returns:
Type Description

A new Expr representing the base-10 logarithm of the numeric value.

logicalMaximum(second, …others)

Creates an expression that returns the larger value between this expression and another expression, based on Firestore's value type ordering.

Parameters:
Name Type Attributes Description
second

The second expression or literal to compare with.

others <repeatable>

Optional additional expressions or literals to compare with.

Returns:
Type Description

A new Expression representing the logical max operation.

Example
```typescript
// Returns the larger value between the 'timestamp' field and the current timestamp.
field("timestamp").logicalMaximum(Function.currentTimestamp());
```

logicalMinimum(second, …others)

Creates an expression that returns the smaller value between this expression and another expression, based on Firestore's value type ordering.

Parameters:
Name Type Attributes Description
second

The second expression or literal to compare with.

others <repeatable>

Optional additional expressions or literals to compare with.

Returns:
Type Description

A new Expression representing the logical min operation.

Example
```typescript
// Returns the smaller value between the 'timestamp' field and the current timestamp.
field("timestamp").logicalMinimum(Function.currentTimestamp());
```

ltrim(valueToTrim)

Trims whitespace or a specified set of characters/bytes from the beginning of a string or byte array.

Parameters:
Name Type Description
valueToTrim

Optional. A string or byte array containing the characters/bytes to trim. If not specified, whitespace will be trimmed.

Returns:
Type Description

A new Expression representing the trimmed string.

Example
```typescript
// Trim whitespace from the beginning of the 'userInput' field
field("userInput").ltrim();

// Trim quotes from the beginning of the 'userInput' field
field("userInput").ltrim('"');
```

mapEntries()

Creates an expression that returns the entries of a map as an array of maps, where each map contains a "k" property for the key and a "v" property for the value. For example: [{ k: "key1", v: "value1" }, ...].

Returns:
Type Description

A new Expression representing the entries of the map.

Example
```typescript
// Get the entries of the 'address' map
field("address").mapEntries();
```

mapGet(subfield)

Accesses a value from a map (object) field using the provided key.

Parameters:
Name Type Description
subfield

The key to access in the map.

Returns:
Type Description

A new Expression representing the value associated with the given key in the map.

Example
```typescript
// Get the 'city' value from the 'address' map field
field("address").mapGet("city");
```

mapKeys()

Creates an expression that returns the keys of a map.

Returns:
Type Description

A new Expression representing the keys of the map.

Example
```typescript
// Get the keys of the 'address' map
field("address").mapKeys();
```

mapMerge(secondMap, …otherMaps)

Creates an expression that merges multiple map values.

// Merges the map in the settings field with, a map literal, and a map in
// that is conditionally returned by another expression
field('settings').mapMerge({ enabled: true }, conditional(field('isAdmin'), { admin: true}, {})
Parameters:
Name Type Attributes Description
secondMap

A required second map to merge. Represented as a literal or an expression that returns a map.

otherMaps <repeatable>

Optional additional maps to merge. Each map is represented as a literal or an expression that returns a map.

Returns:
Type Description

A new FirestoreFunction representing the 'mapMerge' operation.

mapSet(key, value, …moreKeyValues)

Creates an expression that returns a new map with the specified entries added or updated.

Parameters:
Name Type Attributes Description
key

The key to set. Must be a string or a constant string expression.

value

The value to set.

moreKeyValues <repeatable>

Additional key-value pairs to set.

Returns:
Type Description

A new Expression representing the map with the entries set.

Example
```typescript
// Set the 'city' to "San Francisco" in the 'address' map
field("address").mapSet("city", "San Francisco");
```

mapValues()

Creates an expression that returns the values of a map.

Returns:
Type Description

A new Expression representing the values of the map.

Example
```typescript
// Get the values of the 'address' map
field("address").mapValues();
```

maximum()

Creates an aggregation that finds the maximum value of a field across multiple stage inputs.

Returns:
Type Description

A new AggregateFunction representing the 'max' aggregation.

Example
```typescript
// Find the highest score in a leaderboard
field("score").maximum().as("highestScore");
```

minimum()

Creates an aggregation that finds the minimum value of a field across multiple stage inputs.

Returns:
Type Description

A new AggregateFunction representing the 'min' aggregation.

Example
```typescript
// Find the lowest price of all products
field("price").minimum().as("lowestPrice");
```

multiply(second, …others)

Creates an expression that multiplies this expression by another expression.

Parameters:
Name Type Attributes Description
second

The second expression or literal to multiply by.

others <repeatable>

Optional additional expressions or literals to multiply by.

Returns:
Type Description

A new Expression representing the multiplication operation.

Example
```typescript
// Multiply the 'quantity' field by the 'price' field
field("quantity").multiply(field("price"));
```

parent()

Creates an expression that returns the parent document of a document reference.

Returns:
Type Description

A new Expression representing the parent operation.

Example
```typescript
// Get the parent document of a document reference.
field("__path__").parent();
```

reverse()

Creates an expression that reverses this string or bytes expression.

Returns:
Type Description

A new Expression representing the reversed string or bytes.

Example
```typescript
// Reverse the value of the 'myString' field.
field("myString").reverse();
```

rtrim(valueToTrim)

Trims whitespace or a specified set of characters/bytes from the end of a string or byte array.

Parameters:
Name Type Description
valueToTrim

Optional. A string or byte array containing the characters/bytes to trim. If not specified, whitespace will be trimmed.

Returns:
Type Description

A new Expression representing the trimmed string or byte array.

Example
```typescript
// Trim whitespace from the end of the 'userInput' field
field("userInput").rtrim();

// Trim quotes from the end of the 'userInput' field
field("userInput").rtrim('"');
```

sqrt()

Creates an expression that computes the square root of a numeric value.

// Compute the square root of the 'value' field.
field("value").sqrt();
Returns:
Type Description

A new Expression representing the square root of the numeric value.

stringConcat(secondString, …otherStrings)

Creates an expression that concatenates string expressions together.

Parameters:
Name Type Attributes Description
secondString

The additional expression or string literal to concatenate.

otherStrings <repeatable>

Optional additional expressions or string literals to concatenate.

Returns:
Type Description

A new Expression representing the concatenated string.

Example
```typescript
// Combine the 'firstName', " ", and 'lastName' fields into a single string
field("firstName").stringConcat(constant(" "), field("lastName"));
```

stringIndexOf(search)

Creates an expression that finds the index of the first occurrence of a substring or byte sequence.

Parameters:
Name Type Description
search

The substring or byte sequence to search for.

Returns:
Type Description

A new Expression representing the index of the first occurrence.

Example
```typescript
// Find the index of "foo" in the 'text' field
field("text").stringIndexOf("foo");
```

stringRepeat(repetitions)

Creates an expression that repeats a string or byte array a specified number of times.

Parameters:
Name Type Description
repetitions

The number of times to repeat the string or byte array.

Returns:
Type Description

A new Expression representing the repeated string or byte array.

Example
```typescript
// Repeat the 'label' field 3 times
field("label").stringRepeat(3);
```

stringReplaceAll(find, replacement)

Creates an expression that replaces all occurrences of a substring or byte sequence with a replacement.

Parameters:
Name Type Description
find

The substring or byte sequence to search for.

replacement

The replacement string or byte sequence.

Returns:
Type Description

A new Expression representing the string or byte array with replacements.

Example
```typescript
// Replace all occurrences of "foo" with "bar" in the 'text' field
field("text").stringReplaceAll("foo", "bar");
```

stringReplaceOne(find, replacement)

Creates an expression that replaces the first occurrence of a substring or byte sequence with a replacement.

Parameters:
Name Type Description
find

The substring or byte sequence to search for.

replacement

The replacement string or byte sequence.

Returns:
Type Description

A new Expression representing the string or byte array with the replacement.

Example
```typescript
// Replace the first occurrence of "foo" with "bar" in the 'text' field
field("text").stringReplaceOne("foo", "bar");
```

stringReverse()

Creates an expression that reverses a string.

// Reverse the value of the 'myString' field.
field("myString").stringReverse();
Returns:
Type Description

A new Expression representing the reversed string.

sum()

Creates an aggregation that calculates the sum of a numeric field across multiple stage inputs.

Returns:
Type Description

A new AggregateFunction representing the 'sum' aggregation.

Example
```typescript
// Calculate the total revenue from a set of orders
field("orderAmount").sum().as("totalRevenue");
```

timestampToUnixMicros()

Creates an expression that converts this timestamp expression to the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC).

Returns:
Type Description

A new Expression representing the number of microseconds since epoch.

Example
```typescript
// Convert the 'timestamp' field to microseconds since epoch.
field("timestamp").timestampToUnixMicros();
```

timestampToUnixMillis()

Creates an expression that converts this timestamp expression to the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC).

Returns:
Type Description

A new Expression representing the number of milliseconds since epoch.

Example
```typescript
// Convert the 'timestamp' field to milliseconds since epoch.
field("timestamp").timestampToUnixMillis();
```

timestampToUnixSeconds()

Creates an expression that converts this timestamp expression to the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC).

Returns:
Type Description

A new Expression representing the number of seconds since epoch.

Example
```typescript
// Convert the 'timestamp' field to seconds since epoch.
field("timestamp").timestampToUnixSeconds();
```

toLower()

Creates an expression that converts a string to lowercase.

Returns:
Type Description

A new Expression representing the lowercase string.

Example
```typescript
// Convert the 'name' field to lowercase
field("name").toLower();
```

toUpper()

Creates an expression that converts a string to uppercase.

Returns:
Type Description

A new Expression representing the uppercase string.

Example
```typescript
// Convert the 'title' field to uppercase
field("title").toUpper();
```

trim(valueToTrim)

Creates an expression that removes leading and trailing characters from a string or byte array.

Parameters:
Name Type Description
valueToTrim

Optional This parameter is treated as a set of characters or bytes that will be trimmed from the input. If not specified, then whitespace will be trimmed.

Returns:
Type Description

A new Expr representing the trimmed string or byte array.

Example
```typescript
// Trim whitespace from the 'userInput' field
field("userInput").trim();

// Trim quotes from the 'userInput' field
field("userInput").trim('"');
```

type() → {Expression}

Creates an expression that returns the data type of this expression's result, as a string.

Returns:
Type Description
Expression

A new representing the data type.

Example
```typescript
// Get the data type of the value in field 'title'
field('title').type()
```

unixMicrosToTimestamp()

Creates an expression that interprets this expression as the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC) and returns a timestamp.

Returns:
Type Description

A new Expression representing the timestamp.

Example
```typescript
// Interpret the 'microseconds' field as microseconds since epoch.
field("microseconds").unixMicrosToTimestamp();
```

unixMillisToTimestamp()

Creates an expression that interprets this expression as the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC) and returns a timestamp.

Returns:
Type Description

A new Expression representing the timestamp.

Example
```typescript
// Interpret the 'milliseconds' field as milliseconds since epoch.
field("milliseconds").unixMillisToTimestamp();
```

unixSecondsToTimestamp()

Creates an expression that interprets this expression as the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC) and returns a timestamp.

Returns:
Type Description

A new Expression representing the timestamp.

Example
```typescript
// Interpret the 'seconds' field as seconds since epoch.
field("seconds").unixSecondsToTimestamp();
```

vectorLength()

Creates an expression that calculates the length (number of dimensions) of this Firestore Vector expression.

Returns:
Type Description

A new Expression representing the length of the vector.

Example
```typescript
// Get the vector length (dimension) of the field 'embedding'.
field("embedding").vectorLength();
```