@firebase/firestore/lite/pipelines

Functions

Function Description
function()
countAll() Creates an aggregation that counts the total number of stage inputs.
currentDocument() Creates an expression that represents the current document being processed.
currentTimestamp() Creates an expression that evaluates to the current server timestamp.
rand() Creates an expression that generates a random number between 0.0 and 1.0 but not including 1.0.
score() (Public Preview) Evaluates to the search score that reflects the topicality of the document to all of the text predicates (for example: documentMatches) in the search query. If SearchOptions.query is not set or does not contain any text predicates, then this topicality score will always be 0.
function(array, ...)
arrayContains(array, element) Creates an expression that checks if an array expression contains a specific element.
arrayContains(array, element) Creates an expression that checks if an array expression contains a specific element.
arrayContainsAll(array, values) Creates an expression that checks if an array expression contains all the specified elements.
arrayContainsAll(array, arrayExpression) Creates an expression that checks if an array expression contains all the specified elements.
arrayContainsAny(array, values) Creates an expression that checks if an array expression contains any of the specified elements.
arrayContainsAny(array, values) Creates an expression that checks if an array expression contains any of the specified elements.
arrayLength(array) Creates an expression that calculates the length of an array expression.
function(arrayExpression, ...)
arrayFilter(arrayExpression, alias, filter) Creates an expression that filters an array using a provided alias and predicate expression.
arrayFirst(arrayExpression) Creates an expression that returns the first element of an array.
arrayFirstN(arrayExpression, n) Creates an expression that returns the first n elements of an array.
arrayFirstN(arrayExpression, n) Creates an expression that returns the first n elements of an array.
arrayGet(arrayExpression, offset) Creates an expression that indexes into an array from the beginning or end and return the element. If the offset exceeds the array length, an error is returned. A negative offset, starts from the end.
arrayGet(arrayExpression, offsetExpr) Creates an expression that indexes into an array from the beginning or end and return the element. If the offset exceeds the array length, an error is returned. A negative offset, starts from the end.
arrayIndexOf(arrayExpression, search) Creates an expression that returns the first index of the search value in an array. Returns -1 if the value is not found.
arrayIndexOfAll(arrayExpression, search) Creates an expression that returns all indices of the search value in an array.
arrayLast(arrayExpression) Creates an expression that returns the last element of an array.
arrayLastIndexOf(arrayExpression, search) Creates an expression that returns the last index of the search value in an array. Returns -1 if the value is not found.
arrayLastN(arrayExpression, n) Creates an expression that returns the last n elements of an array.
arrayLastN(arrayExpression, n) Creates an expression that returns the last n elements of an array.
arrayMaximum(arrayExpression) Creates an expression that returns the maximum value in an array.
arrayMaximumN(arrayExpression, n) Creates an expression that returns the largest n elements of an array.Note: Returns the n largest non-null elements in the array, in descending order. This does not use a stable sort, meaning the order of equivalent elements is undefined.
arrayMaximumN(arrayExpression, n) Creates an expression that returns the largest n elements of an array.Note: Returns the n largest non-null elements in the array, in descending order. This does not use a stable sort, meaning the order of equivalent elements is undefined.
arrayMinimum(arrayExpression) Creates an expression that returns the minimum value in an array.
arrayMinimumN(arrayExpression, n) Creates an expression that returns the smallest n elements of an array.Note: Returns the n smallest non-null elements in the array, in ascending order. This does not use a stable sort, meaning the order of equivalent elements is undefined.
arrayMinimumN(arrayExpression, n) Creates an expression that returns the smallest n elements of an array.Note: Returns the n smallest non-null elements in the array, in ascending order. This does not use a stable sort, meaning the order of equivalent elements is undefined.
arraySlice(arrayExpression, offset, length) Creates an expression that returns a slice of an array from offset with length elements.
arrayTransform(arrayExpression, elementAlias, transform) Creates an expression that applies a provided transformation to each element in an array.
arrayTransformWithIndex(arrayExpression, 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.
join(arrayExpression, delimiterExpression) Creates an expression that joins the elements of an array into a string.
join(arrayExpression, delimiter) Creates an expression that joins the elements of an array into a string.
function(arrayField, ...)
arrayGet(arrayField, offset) Creates an expression that indexes into an array from the beginning or end and return the element. If the offset exceeds the array length, an error is returned. A negative offset, starts from the end.
arrayGet(arrayField, offsetExpr) Creates an expression that indexes into an array from the beginning or end and return the element. If the offset exceeds the array length, an error is returned. A negative offset, starts from the end.
function(arrayFieldName, ...)
join(arrayFieldName, delimiter) Creates an expression that joins the elements of an array into a string.
join(arrayFieldName, delimiterExpression) Creates an expression that joins the elements of an array into a string.
function(base, ...)
pow(base, exponent) Creates an expression that returns the value of the base expression raised to the power of the exponent expression.
pow(base, exponent) Creates an expression that returns the value of the base expression raised to the power of the exponent.
pow(base, exponent) Creates an expression that returns the value of the base field raised to the power of the exponent expression.
pow(base, exponent) Creates an expression that returns the value of the base field raised to the power of the exponent.
function(booleanExpr, ...)
countIf(booleanExpr) Creates an aggregation that counts the number of stage inputs where the provided boolean expression evaluates to true.
not(booleanExpr) Creates an expression that negates a filter condition.
function(condition, ...)
conditional(condition, thenExpr, elseExpr) Creates a conditional expression that evaluates to a 'then' expression if a condition is true and an 'else' expression if the condition is false.
switchOn(condition, result, others) Creates an expression that evaluates to the result corresponding to the first true condition.
function(documentPath, ...)
documentId(documentPath) Creates an expression that returns the document ID from a path.
parent_2(documentPath) Creates an expression that returns the parent document reference of a document reference.
function(documentPathExpr, ...)
documentId(documentPathExpr) Creates an expression that returns the document ID from a path.
parent_2(documentPathExpr) Creates an expression that returns the parent document reference of a document reference.
function(element, ...)
notEqualAny(element, values) Creates an expression that checks if an expression is not equal to any of the provided values or expressions.
notEqualAny(element, arrayExpression) Creates an expression that checks if an expression is not equal to any of the provided values or expressions.
function(elements, ...)
array(elements) Creates an expression that creates a Firestore array value from an input array.
map(elements) Creates an expression that creates a Firestore map value from an input object.
function(endExpression, ...)
timestampDiff(endExpression, startFieldName, unit) Creates an expression that calculates the difference between two timestamps.
timestampDiff(endExpression, startExpression, unit) Creates an expression that calculates the difference between two timestamps.
function(endFieldName, ...)
timestampDiff(endFieldName, startFieldName, unit)
timestampDiff(endFieldName, startExpression, unit) Creates an expression that calculates the difference between two timestamps.
function(expr, ...)
abs(expr) Creates an expression that computes the absolute value of a numeric value.
ascending(expr) Creates an Ordering that sorts documents in ascending order based on an expression.
byteLength(expr) Creates an expression that calculates the byte length of a string in UTF-8, or just the length of a Blob.
countDistinct(expr) Creates an aggregation that counts the number of distinct values of a field.
descending(expr) Creates an Ordering that sorts documents in descending order based on an expression.
floor(expr) Creates an expression that computes the floor of a numeric value.
timestampToUnixMicros(expr) Creates an expression that converts a timestamp expression to the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC).
timestampToUnixMillis(expr) Creates an expression that converts a timestamp expression to the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC).
timestampToUnixSeconds(expr) Creates an expression that converts a timestamp expression to the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC).
unixMicrosToTimestamp(expr) Creates an expression that interprets an expression as the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC) and returns a timestamp.
unixMillisToTimestamp(expr) Creates an expression that interprets an expression as the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC) and returns a timestamp.
unixSecondsToTimestamp(expr) Creates an expression that interprets an expression as the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC) and returns a timestamp.
function(expression, ...)
arrayAgg(expression) Creates an aggregation that collects all values of an expression across multiple stage inputs into an array.
arrayAggDistinct(expression) Creates an aggregation that collects all distinct values of an expression across multiple stage inputs into an array.
arraySum(expression) Creates an expression that computes the sum of the elements in an array.
average(expression) Creates an aggregation that calculates the average (mean) of values from an expression across multiple stage inputs.
ceil(expression) Creates an expression that computes the ceiling of a numeric value.
coalesce(expression, 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.
collectionId(expression) Creates an expression that returns the collection ID from a path.
count(expression) Creates an aggregation that counts the number of stage inputs with valid evaluations of the provided expression.
divide(expression, value) Creates an expression that divides an expression by a constant value.
equal(expression, value) Creates an expression that checks if an expression is equal to a constant value.
equalAny(expression, values) Creates an expression that checks if an expression, when evaluated, is equal to any of the provided values or expressions.
equalAny(expression, arrayExpression) Creates an expression that checks if an expression is equal to any of the provided values.
exp(expression) Creates an expression that computes e to the power of the expression's result.
first(expression) Creates an aggregation that finds the first value of an expression across multiple stage inputs.
greaterThan(expression, value) Creates an expression that checks if an expression is greater than a constant value.
greaterThanOrEqual(expression, value) Creates an expression that checks if an expression is greater than or equal to a constant value.
isType(expression, type) Creates an expression that checks if the result of an expression is of the given type.
last(expression) Creates an aggregation that finds the last value of an expression across multiple stage inputs.
length_2(expression) Creates an expression that calculates the length of a string, array, map, vector, or bytes.
lessThan(expression, value) Creates an expression that checks if an expression is less than a constant value.
lessThanOrEqual(expression, value) Creates an expression that checks if an expression is less than or equal to a constant value.
ln(expression) Creates an expression that computes the natural logarithm of a numeric value.
log(expression, base) Creates an expression that computes the logarithm of an expression to a given base.
log(expression, base) Creates an expression that computes the logarithm of an expression to a given base.
log10(expression) Creates an expression that computes the base-10 logarithm of a numeric value.
ltrim(expression, valueToTrim) Trims whitespace or a specified set of characters/bytes from the beginning of a string or byte array.
maximum(expression) Creates an aggregation that finds the maximum value of an expression across multiple stage inputs.
minimum(expression) Creates an aggregation that finds the minimum value of an expression across multiple stage inputs.
mod(expression, value) Creates an expression that calculates the modulo (remainder) of dividing an expression by a constant.
notEqual(expression, value) Creates an expression that checks if an expression is not equal to a constant value.
round(expression) Creates an expression that rounds a numeric value to the nearest whole number.
round(expression, decimalPlaces) Creates an expression that rounds a numeric value to the specified number of decimal places.
rtrim(expression, valueToTrim) Trims whitespace or a specified set of characters/bytes from the end of a string or byte array.
split(expression, delimiter) Creates an expression that splits a string into an array of substrings based on the provided delimiter.
split(expression, delimiter) Creates an expression that splits a string into an array of substrings based on the provided delimiter.
sqrt(expression) Creates an expression that computes the square root of a numeric value.
stringIndexOf(expression, search) Creates an expression that finds the index of the first occurrence of a substring or byte sequence.
stringRepeat(expression, repetitions) Creates an expression that repeats a string or byte array a specified number of times.
stringReplaceAll(expression, find, replacement) Creates an expression that replaces all occurrences of a substring or byte sequence with a replacement.
stringReplaceOne(expression, find, replacement) Creates an expression that replaces the first occurrence of a substring or byte sequence with a replacement.
subtract(expression, value) Creates an expression that subtracts a constant value from an expression.
sum(expression) Creates an aggregation that calculates the sum of values from an expression across multiple stage inputs.
trunc(expression) Creates an expression that truncates the numeric value of an expression to an integer.
trunc(expression, decimalPlaces) Creates an expression that truncates a numeric value to the specified number of decimal places.
type(expression) Creates an expression that returns the data type of an expression's result.
function(field, ...)
isAbsent(field) Creates an expression that returns true if a field is absent. Otherwise, returns false even if the field value is null.
reverse(field) Creates an expression that reverses a string value in the specified field.
stringReverse(field) Creates an expression that reverses a string value in the specified field.
substring(field, position, length) Creates an expression that returns a substring of a string or byte array.
substring(field, position, length) Creates an expression that returns a substring of a string or byte array.
function(fieldName, ...)
abs(fieldName) Creates an expression that computes the absolute value of a numeric value.
add(fieldName, second) Creates an expression that adds a field's value to an expression.
arrayAgg(fieldName) Creates an aggregation that collects all values of a field across multiple stage inputs into an array.
arrayAggDistinct(fieldName) Creates an aggregation that collects all distinct values of a field across multiple stage inputs into an array.
arrayContains(fieldName, element) Creates an expression that checks if a field's array value contains a specific element.
arrayContains(fieldName, element) Creates an expression that checks if a field's array value contains a specific value.
arrayContainsAll(fieldName, values) Creates an expression that checks if a field's array value contains all the specified values or expressions.
arrayContainsAll(fieldName, arrayExpression) Creates an expression that checks if a field's array value contains all the specified values or expressions.
arrayContainsAny(fieldName, values) Creates an expression that checks if a field's array value contains any of the specified elements.
arrayContainsAny(fieldName, values) Creates an expression that checks if a field's array value contains any of the specified elements.
arrayFilter(fieldName, alias, filter) Creates an expression that filters an array using a provided alias and predicate expression.
arrayFirst(fieldName) Creates an expression that returns the first element of an array.
arrayFirstN(fieldName, n) Creates an expression that returns the first n elements of an array.
arrayFirstN(fieldName, n) Creates an expression that returns the first n elements of an array.
arrayIndexOf(fieldName, search) Creates an expression that returns the first index of the search value in an array. Returns -1 if the value is not found.
arrayIndexOfAll(fieldName, search) Creates an expression that returns all indices of the search value in an array.
arrayLast(fieldName) Creates an expression that returns the last element of an array.
arrayLastIndexOf(fieldName, search) Creates an expression that returns the last index of the search value in an array. Returns -1 if the value is not found.
arrayLastN(fieldName, n) Creates an expression that returns the last n elements of an array.
arrayLastN(fieldName, n) Creates an expression that returns the last n elements of an array.
arrayLength(fieldName) Creates an expression that calculates the length of an array in a specified field.
arrayMaximum(fieldName) Creates an expression that returns the maximum value in an array.
arrayMaximumN(fieldName, n) Creates an expression that returns the largest n elements of an array.Note: Returns the n largest non-null elements in the array, in descending order. This does not use a stable sort, meaning the order of equivalent elements is undefined.
arrayMaximumN(fieldName, n) Creates an expression that returns the largest n elements of an array.Note: Returns the n largest non-null elements in the array, in descending order. This does not use a stable sort, meaning the order of equivalent elements is undefined.
arrayMinimum(fieldName) Creates an expression that returns the minimum value in an array.
arrayMinimumN(fieldName, n) Creates an expression that returns the smallest n elements of an array.Note: Returns the n smallest non-null elements in the array, in ascending order. This does not use a stable sort, meaning the order of equivalent elements is undefined.
arrayMinimumN(fieldName, n) Creates an expression that returns the smallest n elements of an array.Note: Returns the n smallest non-null elements in the array, in ascending order. This does not use a stable sort, meaning the order of equivalent elements is undefined.
arraySlice(fieldName, offset, length) Creates an expression that returns a slice of an array from offset with length elements.
arraySum(fieldName) Creates an expression that computes the sum of the elements in an array.
arrayTransform(fieldName, elementAlias, transform) Creates an expression that applies a provided transformation to each element in an array.
arrayTransformWithIndex(fieldName, 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.
ascending(fieldName) Creates an Ordering that sorts documents in ascending order based on a field.
average(fieldName) Creates an aggregation that calculates the average (mean) of a field's values across multiple stage inputs.
byteLength(fieldName) Creates an expression that calculates the length of a string represented by a field in UTF-8 bytes, or just the length of a Blob.
ceil(fieldName) Creates an expression that computes the ceiling of a numeric value.
charLength(fieldName) Creates an expression that calculates the character length of a string field in UTF8.
coalesce(fieldName, 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.
collectionId(fieldName) Creates an expression that returns the collection ID from a path.
concat(fieldName, second, others) Creates an expression that concatenates strings, arrays, or blobs. Types cannot be mixed.
cosineDistance(fieldName, vector) Calculates the Cosine distance between a field's vector value and a literal vector value.
cosineDistance(fieldName, vectorExpression) Calculates the Cosine distance between a field's vector value and a vector expression.
count(fieldName) Creates an aggregation that counts the number of stage inputs where the input field exists.
descending(fieldName) Creates an Ordering that sorts documents in descending order based on a field.
divide(fieldName, expressions) Creates an expression that divides a field's value by an expression.
divide(fieldName, value) Creates an expression that divides a field's value by a constant value.
dotProduct(fieldName, vector) Calculates the dot product between a field's vector value and a double array.
dotProduct(fieldName, vectorExpression) Calculates the dot product between a field's vector value and a vector expression.
endsWith(fieldName, suffix) Creates an expression that checks if a field's value ends with a given postfix.
endsWith(fieldName, suffix) Creates an expression that checks if a field's value ends with a given postfix.
equal(fieldName, expression) Creates an expression that checks if a field's value is equal to an expression.
equal(fieldName, value) Creates an expression that checks if a field's value is equal to a constant value.
equalAny(fieldName, values) Creates an expression that checks if a field's value is equal to any of the provided values or expressions.
equalAny(fieldName, arrayExpression) Creates an expression that checks if a field's value is equal to any of the provided values or expressions.
euclideanDistance(fieldName, vector) Calculates the Euclidean distance between a field's vector value and a double array.
euclideanDistance(fieldName, vectorExpression) Calculates the Euclidean distance between a field's vector value and a vector expression.
exists(fieldName) Creates an expression that checks if a field exists.
exp(fieldName) Creates an expression that computes e to the power of the expression's result.
first(fieldName) Creates an aggregation that finds the first value of a field across multiple stage inputs.
floor(fieldName) Creates an expression that computes the floor of a numeric value.
geoDistance(fieldName, location) (Public Preview) Evaluates to the distance in meters between the location in the specified field and the query location.
greaterThan(fieldName, expression) Creates an expression that checks if a field's value is greater than an expression.
greaterThan(fieldName, value) Creates an expression that checks if a field's value is greater than a constant value.
greaterThanOrEqual(fieldName, value) Creates an expression that checks if a field's value is greater than or equal to an expression.
greaterThanOrEqual(fieldName, value) Creates an expression that checks if a field's value is greater than or equal to a constant value.
isType(fieldName, type) Creates an expression that checks if the value in the specified field is of the given type.
last(fieldName) Creates an aggregation that finds the last value of a field across multiple stage inputs.
length_2(fieldName) Creates an expression that calculates the length of a string, array, map, vector, or bytes.
lessThan(fieldName, expression) Creates an expression that checks if a field's value is less than an expression.
lessThan(fieldName, value) Creates an expression that checks if a field's value is less than a constant value.
lessThanOrEqual(fieldName, expression) Creates an expression that checks if a field's value is less than or equal to an expression.
lessThanOrEqual(fieldName, value) Creates an expression that checks if a field's value is less than or equal to a constant value.
like(fieldName, pattern) Creates an expression that performs a case-sensitive wildcard string comparison against a field.
like(fieldName, pattern) Creates an expression that performs a case-sensitive wildcard string comparison against a field.
ln(fieldName) Creates an expression that computes the natural logarithm of a numeric value.
log(fieldName, base) Creates an expression that computes the logarithm of a field to a given base.
log(fieldName, base) Creates an expression that computes the logarithm of a field to a given base.
log10(fieldName) Creates an expression that computes the base-10 logarithm of a numeric value.
logicalMaximum(fieldName, second, others) Creates an expression that returns the largest value between multiple input expressions or literal values. Based on Firestore's value type ordering.
logicalMinimum(fieldName, second, others) Creates an expression that returns the smallest value between a field's value and other input expressions or literal values. Based on Firestore's value type ordering.
ltrim(fieldName, valueToTrim) Trims whitespace or a specified set of characters/bytes from the beginning of a string or byte array.
mapGet(fieldName, subField) Accesses a value from a map (object) field using the provided key.
maximum(fieldName) Creates an aggregation that finds the maximum value of a field across multiple stage inputs.
minimum(fieldName) Creates an aggregation that finds the minimum value of a field across multiple stage inputs.
mod(fieldName, expression) Creates an expression that calculates the modulo (remainder) of dividing a field's value by an expression.
mod(fieldName, value) Creates an expression that calculates the modulo (remainder) of dividing a field's value by a constant.
multiply(fieldName, second) Creates an expression that multiplies a field's value by an expression.
notEqual(fieldName, expression) Creates an expression that checks if a field's value is not equal to an expression.
notEqual(fieldName, value) Creates an expression that checks if a field's value is not equal to a constant value.
notEqualAny(fieldName, values) Creates an expression that checks if a field's value is not equal to any of the provided values or expressions.
notEqualAny(fieldName, arrayExpression) Creates an expression that checks if a field's value is not equal to any of the values in the evaluated expression.
regexContains(fieldName, pattern) Creates an expression that checks if a string field contains a specified regular expression as a substring.
regexContains(fieldName, pattern) Creates an expression that checks if a string field contains a specified regular expression as a substring.
regexFind(fieldName, pattern) Creates an expression that returns the first substring of a string field that matches a specified regular expression.This expression uses the RE2 regular expression syntax.
regexFind(fieldName, pattern) Creates an expression that returns the first substring of a string field that matches a specified regular expression.This expression uses the RE2 regular expression syntax.
regexFindAll(fieldName, pattern) Creates an expression that evaluates to a list of all substrings in a string field that match a specified regular expression.This expression uses the RE2 regular expression syntax.
regexFindAll(fieldName, pattern) Creates an expression that evaluates to a list of all substrings in a string field that match a specified regular expression.This expression uses the RE2 regular expression syntax.
regexMatch(fieldName, pattern) Creates an expression that checks if a string field matches a specified regular expression.
regexMatch(fieldName, pattern) Creates an expression that checks if a string field matches a specified regular expression.
round(fieldName) Creates an expression that rounds a numeric value to the nearest whole number.
round(fieldName, decimalPlaces) Creates an expression that rounds a numeric value to the specified number of decimal places.
rtrim(fieldName, valueToTrim) Trims whitespace or a specified set of characters/bytes from the end of a string or byte array.
split(fieldName, delimiter) Creates an expression that splits the value of a field on the provided delimiter.
split(fieldName, delimiter) Creates an expression that splits the value of a field on the provided delimiter.
sqrt(fieldName) Creates an expression that computes the square root of a numeric value.
startsWith(fieldName, prefix) Creates an expression that checks if a field's value starts with a given prefix.
startsWith(fieldName, prefix) Creates an expression that checks if a field's value starts with a given prefix.
stringConcat(fieldName, secondString, otherStrings) Creates an expression that concatenates string functions, fields or constants together.
stringContains(fieldName, substring) Creates an expression that checks if a string field contains a specified substring.
stringContains(fieldName, substring) Creates an expression that checks if a string field contains a substring specified by an expression.
stringIndexOf(fieldName, search) Creates an expression that finds the index of the first occurrence of a substring or byte sequence.
stringRepeat(fieldName, repetitions) Creates an expression that repeats a string or byte array a specified number of times.
stringReplaceAll(fieldName, find, replacement) Creates an expression that replaces all occurrences of a substring or byte sequence with a replacement.
stringReplaceOne(fieldName, find, replacement) Creates an expression that replaces the first occurrence of a substring or byte sequence with a replacement.
subtract(fieldName, expression) Creates an expression that subtracts an expression from a field's value.
subtract(fieldName, value) Creates an expression that subtracts a constant value from a field's value.
sum(fieldName) Creates an aggregation that calculates the sum of a field's values across multiple stage inputs.
timestampAdd(fieldName, unit, amount) Creates an expression that adds a specified amount of time to a timestamp represented by a field.
timestampExtract(fieldName, part, timezone) Creates an expression that extracts a specified part from a timestamp.
timestampExtract(fieldName, part, timezone) Creates an expression that extracts a specified part from a timestamp.
timestampSubtract(fieldName, unit, amount) Creates an expression that subtracts a specified amount of time from a timestamp represented by a field.
timestampToUnixMicros(fieldName) Creates an expression that converts a timestamp field to the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC).
timestampToUnixMillis(fieldName) Creates an expression that converts a timestamp field to the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC).
timestampToUnixSeconds(fieldName) Creates an expression that converts a timestamp field to the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC).
timestampTruncate(fieldName, granularity, timezone) Creates an expression that truncates a timestamp to a specified granularity.
timestampTruncate(fieldName, granularity, timezone) Creates an expression that truncates a timestamp to a specified granularity.
toLower(fieldName) Creates an expression that converts a string field to lowercase.
toUpper(fieldName) Creates an expression that converts a string field to uppercase.
trim(fieldName, valueToTrim) Creates an expression that removes leading and trailing whitespace from a string or byte array.
trunc(fieldName) Creates an expression that truncates the numeric value of a field to an integer.
trunc(fieldName, decimalPlaces) Creates an expression that truncates a numeric expression to the specified number of decimal places.
type(fieldName) Creates an expression that returns the data type of the data in the specified field.
unixMicrosToTimestamp(fieldName) Creates an expression that interprets a field's value as the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC) and returns a timestamp.
unixMillisToTimestamp(fieldName) Creates an expression that interprets a field's value as the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC) and returns a timestamp.
unixSecondsToTimestamp(fieldName) Creates an expression that interprets a field's value as the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC) and returns a timestamp.
vectorLength(fieldName) Creates an expression that calculates the length of a Firestore Vector represented by a field.
function(first, ...)
add(first, second) Creates an expression that adds two expressions together.
and(first, second, more) Creates an expression that performs a logical 'AND' operation on multiple filter conditions.
concat(first, second, others) Creates an expression that concatenates strings, arrays, or blobs. Types cannot be mixed.
logicalMaximum(first, second, others) Creates an expression that returns the largest value between multiple input expressions or literal values. Based on Firestore's value type ordering.
logicalMinimum(first, second, others) Creates an expression that returns the smallest value between multiple input expressions and literal values. Based on Firestore's value type ordering.
multiply(first, second) Creates an expression that multiplies two expressions together.
nor(first, second, more) Creates an expression that performs a logical 'NOR' operation on multiple filter conditions.
or(first, second, more) Creates an expression that performs a logical 'OR' operation on multiple filter conditions.
xor(first, second, additionalConditions) Creates an expression that performs a logical 'XOR' (exclusive OR) operation on multiple BooleanExpressions.
function(firstArray, ...)
arrayConcat(firstArray, secondArray, otherArrays) Creates an expression that concatenates an array expression with other arrays.
function(firstArrayField, ...)
arrayConcat(firstArrayField, secondArray, otherArrays) Creates an expression that concatenates a field's array value with other arrays.
function(firstMap, ...)
mapMerge(firstMap, secondMap, otherMaps) Creates an expression that merges multiple map values.
function(firstString, ...)
stringConcat(firstString, secondString, otherStrings) Creates an expression that concatenates string expressions together.
function(ifExpr, ...)
ifAbsent(ifExpr, elseExpr) Creates an expression that returns the elseExpr argument if ifExpr is absent, else return the result of the ifExpr argument evaluation.
ifAbsent(ifExpr, elseValue) Creates an expression that returns the elseValue argument if ifExpr is absent, else return the result of the ifExpr argument evaluation.
ifNull(ifExpr, elseExpr) Creates an expression that returns the elseExpr argument if ifExpr is null, else return the result of the ifExpr argument evaluation.
ifNull(ifExpr, elseValue) Creates an expression that returns the elseValue argument if ifExpr is null, else return the result of the ifExpr argument evaluation.
function(ifFieldName, ...)
ifAbsent(ifFieldName, elseExpr) Creates an expression that returns the elseExpr argument if ifFieldName is absent, else return the value of the field.
ifAbsent(ifFieldName, elseValue) Creates an expression that returns the elseValue argument if ifFieldName is absent, else return the value of the field.
ifNull(ifFieldName, elseExpr) Creates an expression that returns the elseExpr argument if ifFieldName field is null, else return the value of the field.
ifNull(ifFieldName, elseValue) Creates an expression that returns the elseValue argument if ifFieldName field is null, else return the value of the field.
function(input, ...)
substring(input, position, length) Creates an expression that returns a substring of a string or byte array.
substring(input, position, length) Creates an expression that returns a substring of a string or byte array.
function(left, ...)
divide(left, right) Creates an expression that divides two expressions.
equal(left, right) Creates an expression that checks if two expressions are equal.
greaterThan(left, right) Creates an expression that checks if the first expression is greater than the second expression.
greaterThanOrEqual(left, right) Creates an expression that checks if the first expression is greater than or equal to the second expression.
lessThan(left, right) Creates an expression that checks if the first expression is less than the second expression.
lessThanOrEqual(left, right) Creates an expression that checks if the first expression is less than or equal to the second expression.
mod(left, right) Creates an expression that calculates the modulo (remainder) of dividing two expressions.
notEqual(left, right) Creates an expression that checks if two expressions are not equal.
subtract(left, right) Creates an expression that subtracts two expressions.
function(mapExpr, ...)
mapRemove(mapExpr, key) Creates an expression that removes a key from the map produced by evaluating an expression.
mapRemove(mapExpr, keyExpr) Creates an expression that removes a key from the map produced by evaluating an expression.
function(mapExpression, ...)
mapEntries(mapExpression) 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" }, ...].
mapGet(mapExpression, subField) Accesses a value from a map (object) expression using the provided key.
mapKeys(mapExpression) Creates an expression that returns the keys of a map.
mapSet(mapExpression, key, value, moreKeyValues) Creates an expression that returns a new map with the specified entries added or updated.
mapValues(mapExpression) Creates an expression that returns the values of a map.
function(mapField, ...)
mapEntries(mapField) 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" }, ...].
mapKeys(mapField) Creates an expression that returns the keys of a map.
mapMerge(mapField, secondMap, otherMaps) Creates an expression that merges multiple map values.
mapRemove(mapField, key) Creates an expression that removes a key from the map at the specified field name.
mapRemove(mapField, keyExpr) Creates an expression that removes a key from the map at the specified field name.
mapSet(mapField, key, value, moreKeyValues) Creates an expression that returns a new map with the specified entries added or updated.
mapValues(mapField) Creates an expression that returns the values of a map.
function(name, ...)
field(name) Creates a Field instance representing the field at the given path.The path can be a simple field name (e.g., "name") or a dot-separated path to a nested field (e.g., "address.city").
variable(name) Creates an expression that retrieves the value of a variable bound via define().
function(options, ...)
subcollection(options) Creates a new Pipeline targeted at a subcollection relative to the current document context. This creates a pipeline without a database instance, suitable for embedding as a subquery. If executed directly, this pipeline will fail.
function(path, ...)
field(path) Creates a Field instance representing the field at the given path.
subcollection(path) Creates a new Pipeline targeted at a subcollection relative to the current document context. This creates a pipeline without a database instance, suitable for embedding as a subquery. If executed directly, this pipeline will fail.
function(pipeline, ...)
execute(pipeline) Executes this pipeline and returns a Promise to represent the asynchronous operation.The returned Promise can be used to track the progress of the pipeline execution and retrieve the results (or handle any errors) asynchronously.The pipeline results are returned as a PipelineSnapshot that contains a list of PipelineResult objects. Each PipelineResult typically represents a single key/value map that has passed through all the stages of the pipeline, however this might differ depending on the stages involved in the pipeline. For example:
  • If there are no stages or only transformation stages, each PipelineResult represents a single document.
  • If there is an aggregation, only a single PipelineResult is returned, representing the aggregated results over the entire dataset .
  • If there is an aggregation stage with grouping, each PipelineResult represents a distinct group and its associated aggregated values.
function(rquery, ...)
documentMatches(rquery) (Public Preview) Perform a full-text search on all indexed search fields in the document.
function(stringExpression, ...)
charLength(stringExpression) Creates an expression that calculates the character length of a string expression in UTF-8.
endsWith(stringExpression, suffix) Creates an expression that checks if a string expression ends with a given postfix.
endsWith(stringExpression, suffix) Creates an expression that checks if a string expression ends with a given postfix.
like(stringExpression, pattern) Creates an expression that performs a case-sensitive wildcard string comparison.
like(stringExpression, pattern) Creates an expression that performs a case-sensitive wildcard string comparison.
regexContains(stringExpression, pattern) Creates an expression that checks if a string expression contains a specified regular expression as a substring.
regexContains(stringExpression, pattern) Creates an expression that checks if a string expression contains a specified regular expression as a substring.
regexFind(stringExpression, pattern) Creates an expression that returns the first substring of a string expression that matches a specified regular expression.This expression uses the RE2 regular expression syntax.
regexFind(stringExpression, pattern) Creates an expression that returns the first substring of a string expression that matches a specified regular expression.This expression uses the RE2 regular expression syntax.
regexFindAll(stringExpression, pattern) Creates an expression that evaluates to a list of all substrings in a string expression that match a specified regular expression.This expression uses the RE2 regular expression syntax.
regexFindAll(stringExpression, pattern) Creates an expression that evaluates to a list of all substrings in a string expression that match a specified regular expression.This expression uses the RE2 regular expression syntax.
regexMatch(stringExpression, pattern) Creates an expression that checks if a string expression matches a specified regular expression.
regexMatch(stringExpression, pattern) Creates an expression that checks if a string expression matches a specified regular expression.
reverse(stringExpression) Creates an expression that reverses a string.
startsWith(stringExpression, prefix) Creates an expression that checks if a string expression starts with a given prefix.
startsWith(stringExpression, prefix) Creates an expression that checks if a string expression starts with a given prefix.
stringContains(stringExpression, substring) Creates an expression that checks if a string expression contains a specified substring.
stringContains(stringExpression, substring) Creates an expression that checks if a string expression contains a substring specified by another expression.
stringReverse(stringExpression) Creates an expression that reverses a string.
toLower(stringExpression) Creates an expression that converts a string expression to lowercase.
toUpper(stringExpression) Creates an expression that converts a string expression to uppercase.
trim(stringExpression, valueToTrim) Creates an expression that removes leading and trailing characters from a string or byte array expression.
function(timestamp, ...)
timestampAdd(timestamp, unit, amount) Creates an expression that adds a specified amount of time to a timestamp.
timestampAdd(timestamp, unit, amount) Creates an expression that adds a specified amount of time to a timestamp.
timestampSubtract(timestamp, unit, amount) Creates an expression that subtracts a specified amount of time from a timestamp.
timestampSubtract(timestamp, unit, amount) Creates an expression that subtracts a specified amount of time from a timestamp.
function(timestampExpression, ...)
timestampExtract(timestampExpression, part, timezone) Creates an expression that extracts a specified part from a timestamp.
timestampExtract(timestampExpression, part, timezone) Creates an expression that extracts a specified part from a timestamp.
timestampTruncate(timestampExpression, granularity, timezone) Creates an expression that truncates a timestamp to a specified granularity.
timestampTruncate(timestampExpression, granularity, timezone) Creates an expression that truncates a timestamp to a specified granularity.
function(tryExpr, ...)
ifError(tryExpr, catchExpr) Creates an expression that returns the catch argument if there is an error, else return the result of the try argument evaluation.This overload is useful when a BooleanExpression is required.
ifError(tryExpr, catchExpr) Creates an expression that returns the catch argument if there is an error, else return the result of the try argument evaluation.
ifError(tryExpr, catchValue) Creates an expression that returns the catch argument if there is an error, else return the result of the try argument evaluation.
function(value, ...)
constant(value) Creates a Constant instance for a number value.
constant(value) Creates a Constant instance for a VectorValue value.
constant(value) Creates a Constant instance for a string value.
constant(value) Creates a BooleanExpression instance for a boolean value.
constant(value) Creates a Constant instance for a null value.
constant(value) Creates a Constant instance for a GeoPoint value.
constant(value) Creates a Constant instance for a Timestamp value.
constant(value) Creates a Constant instance for a Date value.
constant(value) Creates a Constant instance for a Bytes value.
constant(value) Creates a Constant instance for a DocumentReference value.
exists(value) Creates an expression that checks if a field exists.
isAbsent(value) Creates an expression that returns true if a value is absent. Otherwise, returns false even if the value is null.
isError(value) Creates an expression that checks if a given expression produces an error.
function(vectorExpression, ...)
cosineDistance(vectorExpression, vector) Calculates the Cosine distance between a vector expression and a vector literal.
cosineDistance(vectorExpression, otherVectorExpression) Calculates the Cosine distance between two vector expressions.
dotProduct(vectorExpression, vector) Calculates the dot product between a vector expression and a double array.
dotProduct(vectorExpression, otherVectorExpression) Calculates the dot product between two vector expressions.
euclideanDistance(vectorExpression, vector) Calculates the Euclidean distance between a vector expression and a double array.
euclideanDistance(vectorExpression, otherVectorExpression) Calculates the Euclidean distance between two vector expressions.
vectorLength(vectorExpression) Creates an expression that calculates the length of a Firestore Vector.

Classes

Class Description
AggregateFunction A class that represents an aggregate function.
AliasedAggregate An AggregateFunction with alias.
AliasedExpression
BooleanExpression An interface that represents a filter condition.
Bytes An immutable object representing an array of bytes.
CollectionReference A CollectionReference object can be used for adding documents, getting document references, and querying for documents (using query()).
DocumentReference A DocumentReference refers to a document location in a Firestore database and can be used to write, read, or listen to the location. The document at the referenced location may or may not exist.
DocumentSnapshot A DocumentSnapshot contains data read from a document in your Firestore database. The data can be extracted with .data() or .get(<field>) to get a specific field.For a DocumentSnapshot that points to a non-existing document, any data access will return 'undefined'. You can use the exists() method to explicitly verify a document's existence.
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.
Field Represents a reference to a field in a Firestore document, or outputs of a Pipeline stage.

Field references are used to access document field values in expressions and to specify fields for sorting, filtering, and projecting data in Firestore pipelines.

You can create a Field instance using the static method:

FieldPath A FieldPath refers to a field in a document. The path may consist of a single field name (referring to a top-level field in the document), or a list of field names (referring to a nested field in the document).Create a FieldPath by providing field names. If more than one field name is provided, the path will point to a nested field in a document.
FieldValue Sentinel values that can be used when writing document fields with set() or update().
Firestore The Cloud Firestore service interface.Do not call this constructor directly. Instead, use getFirestore().
FunctionExpression This class defines the base class for Firestore Pipeline functions, which can be evaluated within pipeline execution.Typically, you would not use this class or its children directly. Use either the functions like and(), equal(), or the methods on Expression (Expression.equal(), Expression.lessThan(), etc.) to construct new Function instances.
GeoPoint An immutable object representing a geographic location in Firestore. The location is represented as latitude/longitude pair.Latitude values are in the range of [-90, 90]. Longitude values are in the range of [-180, 180].
Ordering Represents an ordering criterion for sorting documents in a Firestore pipeline.You create Ordering instances using the ascending and descending helper functions.
Pipeline The Pipeline class provides a flexible and expressive framework for building complex data transformation and query pipelines for Firestore.A pipeline takes data sources, such as Firestore collections or collection groups, and applies a series of stages that are chained together. Each stage takes the output from the previous stage (or the data source) and produces an output for the next stage (or as the final output of the pipeline).Expressions can be used within each stage to filter and transform data through the stage.NOTE: The chained stages do not prescribe exactly how Firestore will execute the pipeline. Instead, Firestore only guarantees that the result is the same as if the chained stages were executed in order.Usage Examples:
PipelineResult A PipelineResult contains data read from a Firestore Pipeline. The data can be extracted with the PipelineResult.data() or PipelineResult.get() methods.

If the PipelineResult represents a non-document result, ref will return a undefined value.

PipelineSnapshot Represents the results of a Firestore pipeline execution.A PipelineSnapshot contains zero or more PipelineResult objects representing the documents returned by a pipeline query. It provides methods to iterate over the documents and access metadata about the query results.
PipelineSource Provides the entry point for defining the data source of a Firestore Pipeline.Use the methods of this class (e.g., PipelineSource.collection(), PipelineSource.collectionGroup(), PipelineSource.database(), or PipelineSource.documents()) to specify the initial data for your pipeline, such as a collection, a collection group, the entire database, or a set of specific documents.
Query A Query refers to a query which you can read or listen to. You can also construct refined Query objects by adding filters and ordering.
QueryDocumentSnapshot A QueryDocumentSnapshot contains data read from a document in your Firestore database as part of a query. The document is guaranteed to exist and its data can be extracted with .data() or .get(<field>) to get a specific field.A QueryDocumentSnapshot offers the same API surface as a DocumentSnapshot. Since query results contain only existing documents, the exists property will always be true and data() will never return 'undefined'.
Timestamp A Timestamp represents a point in time independent of any time zone or calendar, represented as seconds and fractions of seconds at nanosecond resolution in UTC Epoch time.It is encoded using the Proleptic Gregorian Calendar which extends the Gregorian calendar backwards to year one. It is encoded assuming all minutes are 60 seconds long, i.e. leap seconds are "smeared" so that no leap second table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z.For examples and further specifications, refer to the Timestamp definition.
VectorValue Represents a vector type in Firestore documents. Create an instance with vector().

Interfaces

Interface Description
DocumentData Document data (for use with setDoc()) consists of fields mapped to values.
FirestoreDataConverter Converter used by withConverter() to transform user objects of type AppModelType into Firestore data of type DbModelType.Using the converter allows you to specify generic type arguments when storing and retrieving objects from Firestore.In this context, an "AppModel" is a class that is used in an application to package together related information and functionality. Such a class could, for example, have properties with complex, nested data types, properties used for memoization, properties of types not supported by Firestore (such as symbol and bigint), and helper functions that perform compound operations. Such classes are not suitable and/or possible to store into a Firestore database. Instead, instances of such classes need to be converted to "plain old JavaScript objects" (POJOs) with exclusively primitive properties, potentially nested inside other POJOs or arrays of POJOs. In this context, this type is referred to as the "DbModel" and would be an object suitable for persisting into Firestore. For convenience, applications can implement FirestoreDataConverter and register the converter with Firestore objects, such as DocumentReference or Query, to automatically convert AppModel to DbModel when storing into Firestore, and convert DbModel to AppModel when retrieving from Firestore.
Selectable An interface that represents a selectable expression.

Type Aliases

Type Alias Description
AddFieldsStageOptions Options defining how an AddFieldsStage is evaluated. See Pipeline.addFields().
AggregateStageOptions Options defining how an AggregateStage is evaluated. See Pipeline.aggregate().
CollectionGroupStageOptions Defines the configuration options for a CollectionGroupStage within a pipeline. This type extends StageOptions and provides specific settings for how a collection group is identified and processed during pipeline execution.See PipelineSource.collectionGroup() to create a collection group stage.
CollectionStageOptions Options defining how a CollectionStage is evaluated. See PipelineSource.collection().
DatabaseStageOptions Options defining how a DatabaseStage is evaluated. See PipelineSource.database().
DefineStageOptions Options defining how a DefineStage is evaluated. See Pipeline.define().
DistinctStageOptions Options defining how a DistinctStage is evaluated. See Pipeline.distinct().
DocumentsStageOptions Options defining how a DocumentsStage is evaluated. See PipelineSource.documents().
ExpressionType An enumeration of the different types of expressions.
FindNearestStageOptions Options defining how a FindNearestStage is evaluated. See Pipeline.findNearest().
LimitStageOptions Options defining how a LimitStage is evaluated. See Pipeline.limit().
OffsetStageOptions Options defining how an OffsetStage is evaluated. See Pipeline.offset().
OneOf Utility type to create an type that only allows one property of the Type param T to be set.
PartialWithFieldValue Similar to TypeScript's Partial<T>, but allows nested fields to be omitted and FieldValues to be passed in as property values.
Primitive Primitive types.
RemoveFieldsStageOptions Options defining how a RemoveFieldsStage is evaluated. See Pipeline.removeFields().
ReplaceWithStageOptions Options defining how a ReplaceWithStage is evaluated. See Pipeline.replaceWith().
SampleStageOptions Defines the options for evaluating a sample stage within a pipeline. This type combines common StageOptions with a specific configuration where only one of the defined sampling methods can be applied.See Pipeline.sample() to create a sample stage..
SearchStageOptions (Public Preview) Options defining how a SearchStage is evaluated. See .
SelectStageOptions Options defining how a SelectStage is evaluated. See Pipeline.select().
SetOptions An options object that configures the behavior of setDoc(), and calls. These calls can be configured to perform granular merges instead of overwriting the target documents in their entirety by providing a SetOptions with merge: true.
SortStageOptions Options defining how a SortStage is evaluated. See Pipeline.sort().
StageOptions Options defining how a Stage is evaluated.
SubcollectionStageOptions Options defining how a SubcollectionStage is evaluated.
TimeGranularity Specify time granularity for expressions.
TimePart Specify time parts for timestampExtract expressions.
TimeUnit Specify time units for expressions.
UnionStageOptions Options defining how a UnionStage is evaluated. See Pipeline.union().
UnnestStageOptions Represents the specific options available for configuring an UnnestStage within a pipeline.
WhereStageOptions Options defining how a WhereStage is evaluated. See Pipeline.where().
WithFieldValue Allows FieldValues to be passed in as a property value while maintaining type safety.

function()

countAll()

Creates an aggregation that counts the total number of stage inputs.

Signature:

export declare function countAll(): AggregateFunction;

Returns:

AggregateFunction

A new AggregateFunction representing the 'countAll' aggregation.

Example

// Count the total number of input documents
countAll().as("totalDocument");

currentDocument()

Creates an expression that represents the current document being processed.

Signature:

export declare function currentDocument(): Expression;

Returns:

Expression

An Expression representing the current document.

Example

// Define the current document as a variable "doc"
firestore.pipeline().collection("books")
    .define(currentDocument().as("doc"))
    // Access a field from the defined document variable
    .select(variable("doc").mapGet("title"));

currentTimestamp()

Creates an expression that evaluates to the current server timestamp.

Signature:

export declare function currentTimestamp(): FunctionExpression;

Returns:

FunctionExpression

A new Expression representing the current server timestamp.

Example

// Get the current server timestamp
currentTimestamp()

rand()

Creates an expression that generates a random number between 0.0 and 1.0 but not including 1.0.

Signature:

export declare function rand(): FunctionExpression;

Returns:

FunctionExpression

A new Expression representing the rand operation.

Example

// Generate a random number between 0.0 and 1.0.
rand();

score()

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

Evaluates to the search score that reflects the topicality of the document to all of the text predicates (for example: documentMatches) in the search query. If SearchOptions.query is not set or does not contain any text predicates, then this topicality score will always be 0.

This Expression can only be used within a Search stage.

Signature:

export declare function score(): Expression;

Returns:

Expression

Example

db.pipeline().collection('restaurants').search({
  query: 'waffles',
  sort: score().descending()
})

function(array, ...)

arrayContains(array, element)

Creates an expression that checks if an array expression contains a specific element.

Signature:

export declare function arrayContains(array: Expression, element: Expression): BooleanExpression;

Parameters

Parameter Type Description
array Expression The array expression to check.
element Expression The element to search for in the array.

Returns:

BooleanExpression

A new Expression representing the 'array_contains' comparison.

Example

// Check if the 'colors' array contains the value of field 'selectedColor'
arrayContains(field("colors"), field("selectedColor"));

arrayContains(array, element)

Creates an expression that checks if an array expression contains a specific element.

Signature:

export declare function arrayContains(array: Expression, element: unknown): BooleanExpression;

Parameters

Parameter Type Description
array Expression The array expression to check.
element unknown The element to search for in the array.

Returns:

BooleanExpression

A new Expression representing the 'array_contains' comparison.

Example

// Check if the 'colors' array contains "red"
arrayContains(field("colors"), "red");

arrayContainsAll(array, values)

Creates an expression that checks if an array expression contains all the specified elements.

Signature:

export declare function arrayContainsAll(array: Expression, values: Array<Expression | unknown>): BooleanExpression;

Parameters

Parameter Type Description
array Expression The array expression to check.
values Array<Expression | unknown> The elements to check for in the array.

Returns:

BooleanExpression

A new Expression representing the 'array_contains_all' comparison.

Example

// Check if the "tags" array contains all of the values: "SciFi", "Adventure", and the value from field "tag1"
arrayContainsAll(field("tags"), [field("tag1"), constant("SciFi"), "Adventure"]);

arrayContainsAll(array, arrayExpression)

Creates an expression that checks if an array expression contains all the specified elements.

Signature:

export declare function arrayContainsAll(array: Expression, arrayExpression: Expression): BooleanExpression;

Parameters

Parameter Type Description
array Expression The array expression to check.
arrayExpression Expression The elements to check for in the array.

Returns:

BooleanExpression

A new Expression representing the 'array_contains_all' comparison.

Example

// Check if the "tags" array contains all of the values: "SciFi", "Adventure", and the value from field "tag1"
arrayContainsAll(field("tags"), [field("tag1"), constant("SciFi"), "Adventure"]);

arrayContainsAny(array, values)

Creates an expression that checks if an array expression contains any of the specified elements.

Signature:

export declare function arrayContainsAny(array: Expression, values: Array<Expression | unknown>): BooleanExpression;

Parameters

Parameter Type Description
array Expression The array expression to check.
values Array<Expression | unknown> The elements to check for in the array.

Returns:

BooleanExpression

A new Expression representing the 'array_contains_any' comparison.

Example

// Check if the 'categories' array contains either values from field "cate1" or "Science"
arrayContainsAny(field("categories"), [field("cate1"), "Science"]);

arrayContainsAny(array, values)

Creates an expression that checks if an array expression contains any of the specified elements.

Signature:

export declare function arrayContainsAny(array: Expression, values: Expression): BooleanExpression;

Parameters

Parameter Type Description
array Expression The array expression to check.
values Expression An expression that evaluates to an array, whose elements to check for in the array.

Returns:

BooleanExpression

A new Expression representing the 'array_contains_any' comparison.

Example

// Check if the 'categories' array contains either values from field "cate1" or "Science"
arrayContainsAny(field("categories"), array([field("cate1"), "Science"]));

arrayLength(array)

Creates an expression that calculates the length of an array expression.

Signature:

export declare function arrayLength(array: Expression): FunctionExpression;

Parameters

Parameter Type Description
array Expression The array expression to calculate the length of.

Returns:

FunctionExpression

A new Expression representing the length of the array.

Example

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

function(arrayExpression, ...)

arrayFilter(arrayExpression, alias, filter)

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

Signature:

export declare function arrayFilter(arrayExpression: Expression, alias: string, filter: BooleanExpression): FunctionExpression;

Parameters

Parameter Type Description
arrayExpression Expression The expression representing the array.
alias string The variable name to use for each element.
filter BooleanExpression The predicate boolean expression to filter by.

Returns:

FunctionExpression

A new Expression representing the filtered array.

Example

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

arrayFirst(arrayExpression)

Creates an expression that returns the first element of an array.

Signature:

export declare function arrayFirst(arrayExpression: Expression): FunctionExpression;

Parameters

Parameter Type Description
arrayExpression Expression The expression representing the array.

Returns:

FunctionExpression

A new Expression representing the first element.

Example

// Get the first tag from the 'tags' array field
arrayFirst(field("tags"));

arrayFirstN(arrayExpression, n)

Creates an expression that returns the first n elements of an array.

Signature:

export declare function arrayFirstN(arrayExpression: Expression, n: number): FunctionExpression;

Parameters

Parameter Type Description
arrayExpression Expression The expression representing the array.
n number The number of elements to return.

Returns:

FunctionExpression

A new Expression representing the first n elements.

Example

// Get the first 3 elements from an array expression
arrayFirstN(field("tags"), 3);

arrayFirstN(arrayExpression, n)

Creates an expression that returns the first n elements of an array.

Signature:

export declare function arrayFirstN(arrayExpression: Expression, n: Expression): FunctionExpression;

Parameters

Parameter Type Description
arrayExpression Expression The expression representing the array.
n Expression An expression evaluating to the number of elements to return.

Returns:

FunctionExpression

A new Expression representing the first n elements.

Example

// Get the first n elements from an array expression
arrayFirstN(field("tags"), field("count"));

arrayGet(arrayExpression, offset)

Creates an expression that indexes into an array from the beginning or end and return the element. If the offset exceeds the array length, an error is returned. A negative offset, starts from the end.

Signature:

export declare function arrayGet(arrayExpression: Expression, offset: number): FunctionExpression;

Parameters

Parameter Type Description
arrayExpression Expression An Expression evaluating to an array.
offset number The index of the element to return.

Returns:

FunctionExpression

A new Expression representing the 'arrayGet' operation.

Example

// Return the value in the tags field array at index 1.
arrayGet(field('tags'), 1);

arrayGet(arrayExpression, offsetExpr)

Creates an expression that indexes into an array from the beginning or end and return the element. If the offset exceeds the array length, an error is returned. A negative offset, starts from the end.

Signature:

export declare function arrayGet(arrayExpression: Expression, offsetExpr: Expression): FunctionExpression;

Parameters

Parameter Type Description
arrayExpression Expression An Expression evaluating to an array.
offsetExpr Expression An Expression evaluating to the index of the element to return.

Returns:

FunctionExpression

A new Expression representing the 'arrayGet' operation.

Example

// Return the value in the tags field array at index specified by field
// 'favoriteTag'.
arrayGet(field('tags'), field('favoriteTag'));

arrayIndexOf(arrayExpression, search)

Creates an expression that returns the first index of the search value in an array. Returns -1 if the value is not found.

Signature:

export declare function arrayIndexOf(arrayExpression: Expression, search: unknown | Expression): FunctionExpression;

Parameters

Parameter Type Description
arrayExpression Expression The expression representing the array to search.
search unknown | Expression The value to search for.

Returns:

FunctionExpression

A new Expression representing the index.

Example

// Get the index of "politics" in the 'tags' array field
arrayIndexOf(field("tags"), "politics");

arrayIndexOfAll(arrayExpression, search)

Creates an expression that returns all indices of the search value in an array.

Signature:

export declare function arrayIndexOfAll(arrayExpression: Expression, search: unknown | Expression): FunctionExpression;

Parameters

Parameter Type Description
arrayExpression Expression The expression representing the array to search.
search unknown | Expression The value to search for.

Returns:

FunctionExpression

A new Expression representing the indices.

Example

// Get all indices of 5 in the 'scores' array field
arrayIndexOfAll(field("scores"), 5);

arrayLast(arrayExpression)

Creates an expression that returns the last element of an array.

Signature:

export declare function arrayLast(arrayExpression: Expression): FunctionExpression;

Parameters

Parameter Type Description
arrayExpression Expression The expression representing the array.

Returns:

FunctionExpression

A new Expression representing the last element.

Example

// Get the last tag from the 'tags' array field
arrayLast(field("tags"));

arrayLastIndexOf(arrayExpression, search)

Creates an expression that returns the last index of the search value in an array. Returns -1 if the value is not found.

Signature:

export declare function arrayLastIndexOf(arrayExpression: Expression, search: unknown | Expression): FunctionExpression;

Parameters

Parameter Type Description
arrayExpression Expression The expression representing the array to search.
search unknown | Expression The value to search for.

Returns:

FunctionExpression

A new Expression representing the index.

Example

// Get the last index of "politics" in the 'tags' array field
arrayLastIndexOf(field("tags"), "politics");

arrayLastN(arrayExpression, n)

Creates an expression that returns the last n elements of an array.

Signature:

export declare function arrayLastN(arrayExpression: Expression, n: number): FunctionExpression;

Parameters

Parameter Type Description
arrayExpression Expression The expression representing the array.
n number The number of elements to return.

Returns:

FunctionExpression

A new Expression representing the last n elements.

Example

// Get the last 3 elements from an array expression
arrayLastN(field("tags"), 3);

arrayLastN(arrayExpression, n)

Creates an expression that returns the last n elements of an array.

Signature:

export declare function arrayLastN(arrayExpression: Expression, n: Expression): FunctionExpression;

Parameters

Parameter Type Description
arrayExpression Expression The expression representing the array.
n Expression An expression evaluating to the number of elements to return.

Returns:

FunctionExpression

A new Expression representing the last n elements.

Example

// Get the last n elements from an array expression
arrayLastN(field("tags"), field("count"));

arrayMaximum(arrayExpression)

Creates an expression that returns the maximum value in an array.

Signature:

export declare function arrayMaximum(arrayExpression: Expression): FunctionExpression;

Parameters

Parameter Type Description
arrayExpression Expression The expression representing the array.

Returns:

FunctionExpression

A new Expression representing the maximum value.

Example

// Get the maximum value from the 'scores' array field
arrayMaximum(field("scores"));

arrayMaximumN(arrayExpression, n)

Creates an expression that returns the largest n elements of an array.

Signature:

export declare function arrayMaximumN(arrayExpression: Expression, n: number): FunctionExpression;

Parameters

Parameter Type Description
arrayExpression Expression The expression representing the array.
n number The number of elements to return.

Returns:

FunctionExpression

A new Expression representing the largest n elements.

Example

// Get the top 3 elements from an array expression
arrayMaximumN(field("scores"), 3);

arrayMaximumN(arrayExpression, n)

Creates an expression that returns the largest n elements of an array.

Signature:

export declare function arrayMaximumN(arrayExpression: Expression, n: Expression): FunctionExpression;

Parameters

Parameter Type Description
arrayExpression Expression The expression representing the array.
n Expression An expression evaluating to the number of elements to return.

Returns:

FunctionExpression

A new Expression representing the largest n elements.

Example

// Get the top n elements from an array expression
arrayMaximumN(field("scores"), field("count"));

arrayMinimum(arrayExpression)

Creates an expression that returns the minimum value in an array.

Signature:

export declare function arrayMinimum(arrayExpression: Expression): FunctionExpression;

Parameters

Parameter Type Description
arrayExpression Expression The expression representing the array.

Returns:

FunctionExpression

A new Expression representing the minimum value.

Example

// Get the minimum value from the 'scores' array field
arrayMinimum(field("scores"));

arrayMinimumN(arrayExpression, n)

Creates an expression that returns the smallest n elements of an array.

Signature:

export declare function arrayMinimumN(arrayExpression: Expression, n: number): FunctionExpression;

Parameters

Parameter Type Description
arrayExpression Expression The expression representing the array.
n number The number of elements to return.

Returns:

FunctionExpression

A new Expression representing the smallest n elements.

Example

// Get the bottom 3 scores from the 'scores' array field
arrayMinimumN(field("scores"), 3);

arrayMinimumN(arrayExpression, n)

Creates an expression that returns the smallest n elements of an array.

Signature:

export declare function arrayMinimumN(arrayExpression: Expression, n: Expression): FunctionExpression;

Parameters

Parameter Type Description
arrayExpression Expression The expression representing the array.
n Expression An expression evaluating to the number of elements to return.

Returns:

FunctionExpression

A new Expression representing the smallest n elements.

Example

// Get the bottom n scores from the 'scores' array field
arrayMinimumN(field("scores"), field("count"));

arraySlice(arrayExpression, offset, length)

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

Signature:

export declare function arraySlice(arrayExpression: Expression, offset: number | Expression, length?: number | Expression): FunctionExpression;

Parameters

Parameter Type Description
arrayExpression Expression The expression representing the array.
offset number | Expression The starting offset.
length number | Expression The optional length of the slice.

Returns:

FunctionExpression

A new Expression representing the sliced array.

Example

// Get 5 elements from an array expression starting from index 2
arraySlice(field("items"), 2, 5);

// Get n elements from an array expression starting from index 2
arraySlice(field("items"), 2, field("length"));

arrayTransform(arrayExpression, elementAlias, transform)

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

Signature:

export declare function arrayTransform(arrayExpression: Expression, elementAlias: string, transform: Expression): FunctionExpression;

Parameters

Parameter Type Description
arrayExpression Expression The expression representing the array.
elementAlias string The variable name to use for each element.
transform Expression The lambda expression used to transform the elements.

Returns:

FunctionExpression

A new Expression representing the transformed array.

Example

// Transform "scores" array by multiplying each score by 10
arrayTransform(field("scores"), "score", multiply(variable("score"), 10));

arrayTransformWithIndex(arrayExpression, 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.

Signature:

export declare function arrayTransformWithIndex(arrayExpression: Expression, elementAlias: string, indexAlias: string, transform: Expression): FunctionExpression;

Parameters

Parameter Type Description
arrayExpression Expression The expression representing the array.
elementAlias string The variable name to use for each element.
indexAlias string The variable name to use for the current index.
transform Expression The expression used to transform the elements.

Returns:

FunctionExpression

A new Expression representing the transformed array.

Example

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

join(arrayExpression, delimiterExpression)

Creates an expression that joins the elements of an array into a string.

Signature:

export declare function join(arrayExpression: Expression, delimiterExpression: Expression): Expression;

Parameters

Parameter Type Description
arrayExpression Expression An expression that evaluates to an array.
delimiterExpression Expression The expression that evaluates to the delimiter string.

Returns:

Expression

A new Expression representing the join operation.

Example

// Join an array of string using the delimiter from the 'separator' field.
join(array(['foo', 'bar']), field("separator"))

join(arrayExpression, delimiter)

Creates an expression that joins the elements of an array into a string.

Signature:

export declare function join(arrayExpression: Expression, delimiter: string): Expression;

Parameters

Parameter Type Description
arrayExpression Expression An expression that evaluates to an array.
delimiter string The string to use as a delimiter.

Returns:

Expression

A new Expression representing the join operation.

Example

// Join the elements of the 'tags' field with a comma and space.
join(field("tags"), ", ")

function(arrayField, ...)

arrayGet(arrayField, offset)

Creates an expression that indexes into an array from the beginning or end and return the element. If the offset exceeds the array length, an error is returned. A negative offset, starts from the end.

Signature:

export declare function arrayGet(arrayField: string, offset: number): FunctionExpression;

Parameters

Parameter Type Description
arrayField string The name of the array field.
offset number The index of the element to return.

Returns:

FunctionExpression

A new Expression representing the 'arrayGet' operation.

Example

// Return the value in the tags field array at index 1.
arrayGet('tags', 1);

arrayGet(arrayField, offsetExpr)

Creates an expression that indexes into an array from the beginning or end and return the element. If the offset exceeds the array length, an error is returned. A negative offset, starts from the end.

Signature:

export declare function arrayGet(arrayField: string, offsetExpr: Expression): FunctionExpression;

Parameters

Parameter Type Description
arrayField string The name of the array field.
offsetExpr Expression An Expression evaluating to the index of the element to return.

Returns:

FunctionExpression

A new Expression representing the 'arrayGet' operation.

Example

// Return the value in the tags field array at index specified by field
// 'favoriteTag'.
arrayGet('tags', field('favoriteTag'));

function(arrayFieldName, ...)

join(arrayFieldName, delimiter)

Creates an expression that joins the elements of an array into a string.

Signature:

export declare function join(arrayFieldName: string, delimiter: string): Expression;

Parameters

Parameter Type Description
arrayFieldName string The name of the field containing the array.
delimiter string The string to use as a delimiter.

Returns:

Expression

A new Expression representing the join operation.

Example

// Join the elements of the 'tags' field with a comma and space.
join("tags", ", ")

join(arrayFieldName, delimiterExpression)

Creates an expression that joins the elements of an array into a string.

Signature:

export declare function join(arrayFieldName: string, delimiterExpression: Expression): Expression;

Parameters

Parameter Type Description
arrayFieldName string The name of the field containing the array.
delimiterExpression Expression The expression that evaluates to the delimiter string.

Returns:

Expression

A new Expression representing the join operation.

Example

// Join the elements of the 'tags' field with the delimiter from the 'separator' field.
join('tags', field("separator"))

function(base, ...)

pow(base, exponent)

Creates an expression that returns the value of the base expression raised to the power of the exponent expression.

Signature:

export declare function pow(base: Expression, exponent: Expression): FunctionExpression;

Parameters

Parameter Type Description
base Expression The expression to raise to the power of the exponent.
exponent Expression The expression to raise the base to the power of.

Returns:

FunctionExpression

A new Expression representing the power operation.

Example

// Raise the value of the 'base' field to the power of the 'exponent' field.
pow(field("base"), field("exponent"));

pow(base, exponent)

Creates an expression that returns the value of the base expression raised to the power of the exponent.

Signature:

export declare function pow(base: Expression, exponent: number): FunctionExpression;

Parameters

Parameter Type Description
base Expression The expression to raise to the power of the exponent.
exponent number The constant value to raise the base to the power of.

Returns:

FunctionExpression

A new Expression representing the power operation.

Example

// Raise the value of the 'base' field to the power of 2.
pow(field("base"), 2);

pow(base, exponent)

Creates an expression that returns the value of the base field raised to the power of the exponent expression.

Signature:

export declare function pow(base: string, exponent: Expression): FunctionExpression;

Parameters

Parameter Type Description
base string The name of the field to raise to the power of the exponent.
exponent Expression The expression to raise the base to the power of.

Returns:

FunctionExpression

A new Expression representing the power operation.

Example

// Raise the value of the 'base' field to the power of the 'exponent' field.
pow("base", field("exponent"));

pow(base, exponent)

Creates an expression that returns the value of the base field raised to the power of the exponent.

Signature:

export declare function pow(base: string, exponent: number): FunctionExpression;

Parameters

Parameter Type Description
base string The name of the field to raise to the power of the exponent.
exponent number The constant value to raise the base to the power of.

Returns:

FunctionExpression

A new Expression representing the power operation.

Example

// Raise the value of the 'base' field to the power of 2.
pow("base", 2);

function(booleanExpr, ...)

countIf(booleanExpr)

Creates an aggregation that counts the number of stage inputs where the provided boolean expression evaluates to true.

Signature:

export declare function countIf(booleanExpr: BooleanExpression): AggregateFunction;

Parameters

Parameter Type Description
booleanExpr BooleanExpression The boolean expression to evaluate on each input.

Returns:

AggregateFunction

A new AggregateFunction representing the 'countIf' aggregation.

Example

// Count the number of documents where 'is_active' field equals true
countIf(field("is_active").equal(true)).as("numActiveDocuments");

not(booleanExpr)

Creates an expression that negates a filter condition.

Signature:

export declare function not(booleanExpr: BooleanExpression): BooleanExpression;

Parameters

Parameter Type Description
booleanExpr BooleanExpression The filter condition to negate.

Returns:

BooleanExpression

A new Expression representing the negated filter condition.

Example

// Find documents where the 'completed' field is NOT true
not(equal("completed", true));

function(condition, ...)

conditional(condition, thenExpr, elseExpr)

Creates a conditional expression that evaluates to a 'then' expression if a condition is true and an 'else' expression if the condition is false.

Signature:

export declare function conditional(condition: BooleanExpression, thenExpr: Expression, elseExpr: Expression): FunctionExpression;

Parameters

Parameter Type Description
condition BooleanExpression The condition to evaluate.
thenExpr Expression The expression to evaluate if the condition is true.
elseExpr Expression The expression to evaluate if the condition is false.

Returns:

FunctionExpression

A new Expression representing the conditional expression.

Example

// If 'age' is greater than 18, return "Adult"; otherwise, return "Minor".
conditional(
    greaterThan("age", 18), constant("Adult"), constant("Minor"));

switchOn(condition, result, others)

Creates an expression that evaluates to the result corresponding to the first true condition.

This function behaves like a switch statement. It accepts an alternating sequence of conditions and their corresponding results. If an odd number of arguments is provided, the final argument serves as a default fallback result. If no default is provided and no condition evaluates to true, it throws an error.

Signature:

export declare function switchOn(condition: BooleanExpression, result: Expression, ...others: Array<BooleanExpression | Expression>): FunctionExpression;

Parameters

Parameter Type Description
condition BooleanExpression The first condition to check.
result Expression The result if the first condition is true.
others Array<BooleanExpression | Expression> Additional conditions and results, and optionally a default value.

Returns:

FunctionExpression

A new Expression representing the switch operation.

Example

// Return "Active" if field "status" is 1, "Pending" if field "status" is 2,
// and default to "Unknown" if none of the conditions are true.
switchOn(
  equal(field("status"), 1), constant("Active"),
  equal(field("status"), 2), constant("Pending"),
  constant("Unknown")
)

function(documentPath, ...)

documentId(documentPath)

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

Signature:

export declare function documentId(documentPath: string | DocumentReference): FunctionExpression;

Parameters

Parameter Type Description
documentPath string | DocumentReference

Returns:

FunctionExpression

A new Expression representing the documentId operation.

Example

// Get the document ID from a path.
documentId(myDocumentReference);

parent_2(documentPath)

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

Signature:

declare function parent_2(documentPath: string | DocumentReference): FunctionExpression;

Parameters

Parameter Type Description
documentPath string | DocumentReference A string path or DocumentReference to get the parent from.

Returns:

FunctionExpression

A new Expression representing the parent operation.

Example

// Get the parent document reference of a document reference.
parent(myDocumentReference);

function(documentPathExpr, ...)

documentId(documentPathExpr)

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

Signature:

export declare function documentId(documentPathExpr: Expression): FunctionExpression;

Parameters

Parameter Type Description
documentPathExpr Expression

Returns:

FunctionExpression

A new Expression representing the documentId operation.

Example

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

parent_2(documentPathExpr)

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

Signature:

declare function parent_2(documentPathExpr: Expression): FunctionExpression;

Parameters

Parameter Type Description
documentPathExpr Expression An Expression evaluating to a document reference.

Returns:

FunctionExpression

A new Expression representing the parent operation.

Example

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

function(element, ...)

notEqualAny(element, values)

Creates an expression that checks if an expression is not equal to any of the provided values or expressions.

Signature:

export declare function notEqualAny(element: Expression, values: Array<Expression | unknown>): BooleanExpression;

Parameters

Parameter Type Description
element Expression The expression to compare.
values Array<Expression | unknown> The values to check against.

Returns:

BooleanExpression

A new Expression representing the 'NOT IN' comparison.

Example

// Check if the 'status' field is neither "pending" nor the value of 'rejectedStatus'
notEqualAny(field("status"), ["pending", field("rejectedStatus")]);

notEqualAny(element, arrayExpression)

Creates an expression that checks if an expression is not equal to any of the provided values or expressions.

Signature:

export declare function notEqualAny(element: Expression, arrayExpression: Expression): BooleanExpression;

Parameters

Parameter Type Description
element Expression The expression to compare.
arrayExpression Expression The values to check against.

Returns:

BooleanExpression

A new Expression representing the 'NOT IN' comparison.

Example

// Check if the 'status' field is neither "pending" nor the value of the field 'rejectedStatus'
notEqualAny(field("status"), ["pending", field("rejectedStatus")]);

function(elements, ...)

array(elements)

Creates an expression that creates a Firestore array value from an input array.

Signature:

export declare function array(elements: unknown[]): FunctionExpression;

Parameters

Parameter Type Description
elements unknown[] The input array to evaluate in the expression.

Returns:

FunctionExpression

A new Expression representing the array function.

Example

// Create an array value from the input array and reference the 'baz' field value from the input document.
array(['bar', field('baz')]).as('foo');

map(elements)

Creates an expression that creates a Firestore map value from an input object.

Signature:

export declare function map(elements: Record<string, unknown>): FunctionExpression;

Parameters

Parameter Type Description
elements Record<string, unknown> The input map to evaluate in the expression.

Returns:

FunctionExpression

A new Expression representing the map function.

Example

// Create a map from the input object and reference the 'baz' field value from the input document.
map({foo: 'bar', baz: field('baz')}).as('data');

function(endExpression, ...)

timestampDiff(endExpression, startFieldName, unit)

Creates an expression that calculates the difference between two timestamps.

Signature:

export declare function timestampDiff(endExpression: Expression, startFieldName: string, unit: TimeUnit | Expression): FunctionExpression;

Parameters

Parameter Type Description
endExpression Expression The ending timestamp for the difference calculation.
startFieldName string The name of the field representing the starting timestamp.
unit TimeUnit | Expression The unit of time for the difference (e.g., "day", "hour").

Returns:

FunctionExpression

A new Expression representing the difference as an integer.

Example

// Calculate the difference in days between an ending timestamp expression and 'startTime' field.
timestampDiff(field('endTime'), 'startTime', 'day')

timestampDiff(endExpression, startExpression, unit)

Creates an expression that calculates the difference between two timestamps.

Signature:

export declare function timestampDiff(endExpression: Expression, startExpression: Expression, unit: TimeUnit | Expression): FunctionExpression;

Parameters

Parameter Type Description
endExpression Expression The ending timestamp for the difference calculation.
startExpression Expression The starting timestamp for the difference calculation.
unit TimeUnit | Expression The unit of time for the difference (e.g., "day", "hour").

Returns:

FunctionExpression

A new Expression representing the difference as an integer.

Example

// Calculate the difference in days between two timestamp expressions.
timestampDiff(field('endTime'), field('startTime'), 'day')

function(endFieldName, ...)

timestampDiff(endFieldName, startFieldName, unit)

Signature:

export declare function timestampDiff(endFieldName: string, startFieldName: string, unit: TimeUnit | Expression): FunctionExpression;

Parameters

Parameter Type Description
endFieldName string
startFieldName string
unit TimeUnit | Expression

Returns:

FunctionExpression

timestampDiff(endFieldName, startExpression, unit)

Creates an expression that calculates the difference between two timestamps.

Signature:

export declare function timestampDiff(endFieldName: string, startExpression: Expression, unit: TimeUnit | Expression): FunctionExpression;

Parameters

Parameter Type Description
endFieldName string The name of the field representing the ending timestamp.
startExpression Expression The starting timestamp for the difference calculation.
unit TimeUnit | Expression The unit of time for the difference (e.g., "day", "hour").

Returns:

FunctionExpression

A new Expression representing the difference as an integer.

Example

// Calculate the difference in days between 'endTime' field and a starting timestamp expression.
timestampDiff('endTime', field('startTime'), 'day')

function(expr, ...)

abs(expr)

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

Signature:

export declare function abs(expr: Expression): FunctionExpression;

Parameters

Parameter Type Description
expr Expression The expression to compute the absolute value of.

Returns:

FunctionExpression

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

ascending(expr)

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

Signature:

export declare function ascending(expr: Expression): Ordering;

Parameters

Parameter Type Description
expr Expression The expression to create an ascending ordering for.

Returns:

Ordering

A new Ordering for ascending sorting.

Example

// Sort documents by the 'name' field in lowercase in ascending order
firestore.pipeline().collection("users")
  .sort(ascending(field("name").toLower()));

byteLength(expr)

Creates an expression that calculates the byte length of a string in UTF-8, or just the length of a Blob.

Signature:

export declare function byteLength(expr: Expression): FunctionExpression;

Parameters

Parameter Type Description
expr Expression The expression representing the string.

Returns:

FunctionExpression

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

Example

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

countDistinct(expr)

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

Signature:

export declare function countDistinct(expr: Expression | string): AggregateFunction;

Parameters

Parameter Type Description
expr Expression | string The expression or field to count distinct values of.

Returns:

AggregateFunction

A new AggregateFunction representing the 'count_distinct' aggregation.

descending(expr)

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

Signature:

export declare function descending(expr: Expression): Ordering;

Parameters

Parameter Type Description
expr Expression The expression to create a descending ordering for.

Returns:

Ordering

A new Ordering for descending sorting.

Example

// Sort documents by the 'name' field in lowercase in descending order
firestore.pipeline().collection("users")
  .sort(descending(field("name").toLower()));

floor(expr)

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

Signature:

export declare function floor(expr: Expression): FunctionExpression;

Parameters

Parameter Type Description
expr Expression The expression to compute the floor of.

Returns:

FunctionExpression

A new Expression representing the floor of the numeric value.

timestampToUnixMicros(expr)

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

Signature:

export declare function timestampToUnixMicros(expr: Expression): FunctionExpression;

Parameters

Parameter Type Description
expr Expression The expression representing the timestamp.

Returns:

FunctionExpression

A new Expression representing the number of microseconds since epoch.

Example

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

timestampToUnixMillis(expr)

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

Signature:

export declare function timestampToUnixMillis(expr: Expression): FunctionExpression;

Parameters

Parameter Type Description
expr Expression The expression representing the timestamp.

Returns:

FunctionExpression

A new Expression representing the number of milliseconds since epoch.

Example

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

timestampToUnixSeconds(expr)

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

Signature:

export declare function timestampToUnixSeconds(expr: Expression): FunctionExpression;

Parameters

Parameter Type Description
expr Expression The expression representing the timestamp.

Returns:

FunctionExpression

A new Expression representing the number of seconds since epoch.

Example

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

unixMicrosToTimestamp(expr)

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

Signature:

export declare function unixMicrosToTimestamp(expr: Expression): FunctionExpression;

Parameters

Parameter Type Description
expr Expression The expression representing the number of microseconds since epoch.

Returns:

FunctionExpression

A new Expression representing the timestamp.

Example

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

unixMillisToTimestamp(expr)

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

Signature:

export declare function unixMillisToTimestamp(expr: Expression): FunctionExpression;

Parameters

Parameter Type Description
expr Expression The expression representing the number of milliseconds since epoch.

Returns:

FunctionExpression

A new Expression representing the timestamp.

Example

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

unixSecondsToTimestamp(expr)

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

Signature:

export declare function unixSecondsToTimestamp(expr: Expression): FunctionExpression;

Parameters

Parameter Type Description
expr Expression The expression representing the number of seconds since epoch.

Returns:

FunctionExpression

A new Expression representing the timestamp.

Example

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

function(expression, ...)

arrayAgg(expression)

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

If the expression resolves to an absent value, it is converted to null. The order of elements in the output array is not stable and shouldn't be relied upon.

Signature:

export declare function arrayAgg(expression: Expression): AggregateFunction;

Parameters

Parameter Type Description
expression Expression The expression to collect values from.

Returns:

AggregateFunction

A new AggregateFunction representing the 'array_agg' aggregation.

Example

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

arrayAggDistinct(expression)

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

If the expression resolves to an absent value, it is converted to null. The order of elements in the output array is not stable and shouldn't be relied upon.

Signature:

export declare function arrayAggDistinct(expression: Expression): AggregateFunction;

Parameters

Parameter Type Description
expression Expression The expression to collect values from.

Returns:

AggregateFunction

A new AggregateFunction representing the 'array_agg_distinct' aggregation.

Example

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

arraySum(expression)

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

Signature:

export declare function arraySum(expression: Expression): FunctionExpression;

Parameters

Parameter Type Description
expression Expression An expression evaluating to a numeric array, which the sum will be computed for.

Returns:

FunctionExpression

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

Example

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

average(expression)

Creates an aggregation that calculates the average (mean) of values from an expression across multiple stage inputs.

Signature:

export declare function average(expression: Expression): AggregateFunction;

Parameters

Parameter Type Description
expression Expression The expression representing the values to average.

Returns:

AggregateFunction

A new AggregateFunction representing the 'average' aggregation.

Example

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

ceil(expression)

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

Signature:

export declare function ceil(expression: Expression): FunctionExpression;

Parameters

Parameter Type Description
expression Expression An expression evaluating to a numeric value, which the ceiling will be computed for.

Returns:

FunctionExpression

A new Expression representing the ceiling of the numeric value.

Example

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

coalesce(expression, 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.

Signature:

export declare function coalesce(expression: Expression, replacement: Expression | unknown, ...others: Array<Expression | unknown>): FunctionExpression;

Parameters

Parameter Type Description
expression Expression The first expression to check for null.
replacement Expression | unknown The fallback expression or value if the first one is null.
others Array<Expression | unknown> Optional additional expressions to check if previous ones are null.

Returns:

FunctionExpression

A new Expression representing the coalesce operation.

Example

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

collectionId(expression)

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

Signature:

export declare function collectionId(expression: Expression): FunctionExpression;

Parameters

Parameter Type Description
expression Expression An expression evaluating to a path, which the collection ID will be extracted from.

Returns:

FunctionExpression

A new Expression representing the collectionId operation.

Example

// Get the collection ID from a path.
collectionId(field("__name__"));

count(expression)

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

Signature:

export declare function count(expression: Expression): AggregateFunction;

Parameters

Parameter Type Description
expression Expression The expression to count.

Returns:

AggregateFunction

A new AggregateFunction representing the 'count' aggregation.

Example

// Count the number of items where the price is greater than 10
count(field("price").greaterThan(10)).as("expensiveItemCount");

divide(expression, value)

Creates an expression that divides an expression by a constant value.

Signature:

export declare function divide(expression: Expression, value: unknown): FunctionExpression;

Parameters

Parameter Type Description
expression Expression The expression to be divided.
value unknown The constant value to divide by.

Returns:

FunctionExpression

A new Expression representing the division operation.

Example

// Divide the 'value' field by 10
divide(field("value"), 10);

equal(expression, value)

Creates an expression that checks if an expression is equal to a constant value.

Signature:

export declare function equal(expression: Expression, value: unknown): BooleanExpression;

Parameters

Parameter Type Description
expression Expression The expression to compare.
value unknown The constant value to compare to.

Returns:

BooleanExpression

A new Expression representing the equality comparison.

Example

// Check if the 'age' field is equal to 21
equal(field("age"), 21);

equalAny(expression, values)

Creates an expression that checks if an expression, when evaluated, is equal to any of the provided values or expressions.

Signature:

export declare function equalAny(expression: Expression, values: Array<Expression | unknown>): BooleanExpression;

Parameters

Parameter Type Description
expression Expression The expression whose results to compare.
values Array<Expression | unknown> The values to check against.

Returns:

BooleanExpression

A new Expression representing the 'IN' comparison.

Example

// Check if the 'category' field is either "Electronics" or value of field 'primaryType'
equalAny(field("category"), [constant("Electronics"), field("primaryType")]);

equalAny(expression, arrayExpression)

Creates an expression that checks if an expression is equal to any of the provided values.

Signature:

export declare function equalAny(expression: Expression, arrayExpression: Expression): BooleanExpression;

Parameters

Parameter Type Description
expression Expression The expression whose results to compare.
arrayExpression Expression An expression that evaluates to an array, whose elements to check for equality to the input.

Returns:

BooleanExpression

A new Expression representing the 'IN' comparison.

Example

// Check if the 'category' field is set to a value in the disabledCategories field
equalAny(field("category"), field('disabledCategories'));

exp(expression)

Creates an expression that computes e to the power of the expression's result.

Signature:

export declare function exp(expression: Expression): FunctionExpression;

Parameters

Parameter Type Description
expression Expression

Returns:

FunctionExpression

A new Expression representing the exp of the numeric value.

Example

// Compute e to the power of 2.
exp(constant(2));

first(expression)

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

Signature:

export declare function first(expression: Expression): AggregateFunction;

Parameters

Parameter Type Description
expression Expression The expression to find the first value of.

Returns:

AggregateFunction

A new AggregateFunction representing the 'first' aggregation.

Example

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

greaterThan(expression, value)

Creates an expression that checks if an expression is greater than a constant value.

Signature:

export declare function greaterThan(expression: Expression, value: unknown): BooleanExpression;

Parameters

Parameter Type Description
expression Expression The expression to compare.
value unknown The constant value to compare to.

Returns:

BooleanExpression

A new Expression representing the greater than comparison.

Example

// Check if the 'age' field is greater than 18
greaterThan(field("age"), 18);

greaterThanOrEqual(expression, value)

Creates an expression that checks if an expression is greater than or equal to a constant value.

Signature:

export declare function greaterThanOrEqual(expression: Expression, value: unknown): BooleanExpression;

Parameters

Parameter Type Description
expression Expression The expression to compare.
value unknown The constant value to compare to.

Returns:

BooleanExpression

A new Expression representing the greater than or equal to comparison.

Example

// Check if the 'quantity' field is greater than or equal to 10
greaterThanOrEqual(field("quantity"), 10);

isType(expression, type)

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

Null or undefined fields evaluate to skip/error. Use ifAbsent() / isAbsent() to evaluate missing data. Supported values for type are: 'null', 'array', 'boolean', 'bytes', 'timestamp', 'geo_point', 'number', 'int32', 'int64', 'float64', 'decimal128', 'map', 'reference', 'string', 'vector', 'max_key', 'min_key', 'object_id', 'regex', 'request_timestamp'.

Signature:

export declare function isType(expression: Expression, type: string): BooleanExpression;

Parameters

Parameter Type Description
expression Expression The expression to check.
type string The type to check for.

Returns:

BooleanExpression

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

Example

// Check if the result of a calculation is a number
isType(add('count', 1), 'number')

last(expression)

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

Signature:

export declare function last(expression: Expression): AggregateFunction;

Parameters

Parameter Type Description
expression Expression The expression to find the last value of.

Returns:

AggregateFunction

A new AggregateFunction representing the 'last' aggregation.

Example

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

length_2(expression)

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

Signature:

declare function length_2(expression: Expression): FunctionExpression;

Parameters

Parameter Type Description
expression Expression An expression evaluating to a string, array, map, vector, or bytes, which the length will be calculated for.

Returns:

FunctionExpression

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

Example

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

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

lessThan(expression, value)

Creates an expression that checks if an expression is less than a constant value.

Signature:

export declare function lessThan(expression: Expression, value: unknown): BooleanExpression;

Parameters

Parameter Type Description
expression Expression The expression to compare.
value unknown The constant value to compare to.

Returns:

BooleanExpression

A new Expression representing the less than comparison.

Example

// Check if the 'age' field is less than 30
lessThan(field("age"), 30);

lessThanOrEqual(expression, value)

Creates an expression that checks if an expression is less than or equal to a constant value.

Signature:

export declare function lessThanOrEqual(expression: Expression, value: unknown): BooleanExpression;

Parameters

Parameter Type Description
expression Expression The expression to compare.
value unknown The constant value to compare to.

Returns:

BooleanExpression

A new Expression representing the less than or equal to comparison.

Example

// Check if the 'quantity' field is less than or equal to 20
lessThan(field("quantity"), 20);

ln(expression)

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

Signature:

export declare function ln(expression: Expression): FunctionExpression;

Parameters

Parameter Type Description
expression Expression An expression evaluating to a numeric value, which the natural logarithm will be computed for.

Returns:

FunctionExpression

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

Example

// Compute the natural logarithm of the 'value' field.
ln(field("value"));

log(expression, base)

Creates an expression that computes the logarithm of an expression to a given base.

Signature:

export declare function log(expression: Expression, base: number): FunctionExpression;

Parameters

Parameter Type Description
expression Expression An expression evaluating to a numeric value, which the logarithm will be computed for.
base number The base of the logarithm.

Returns:

FunctionExpression

A new Expression representing the logarithm of the numeric value.

Example

// Compute the logarithm of the 'value' field with base 10.
log(field("value"), 10);

log(expression, base)

Creates an expression that computes the logarithm of an expression to a given base.

Signature:

export declare function log(expression: Expression, base: Expression): FunctionExpression;

Parameters

Parameter Type Description
expression Expression An expression evaluating to a numeric value, which the logarithm will be computed for.
base Expression The base of the logarithm.

Returns:

FunctionExpression

A new Expression representing the logarithm of the numeric value.

Example

// Compute the logarithm of the 'value' field with the base in the 'base' field.
log(field("value"), field("base"));

log10(expression)

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

Signature:

export declare function log10(expression: Expression): FunctionExpression;

Parameters

Parameter Type Description
expression Expression An expression evaluating to a numeric value, which the base-10 logarithm will be computed for.

Returns:

FunctionExpression

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

Example

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

ltrim(expression, valueToTrim)

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

Signature:

export declare function ltrim(expression: Expression, valueToTrim?: string | Expression | Bytes): FunctionExpression;

Parameters

Parameter Type Description
expression Expression The expression representing the string or byte array.
valueToTrim string | Expression | Bytes Optional. A string or byte array containing the characters/bytes to trim. If not specified, whitespace will be trimmed.

Returns:

FunctionExpression

A new Expression representing the trimmed string or byte array.

Example

// Trim whitespace from the beginning of the 'userInput' field
ltrim(field("userInput"));

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

maximum(expression)

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

Signature:

export declare function maximum(expression: Expression): AggregateFunction;

Parameters

Parameter Type Description
expression Expression The expression to find the maximum value of.

Returns:

AggregateFunction

A new AggregateFunction representing the 'maximum' aggregation.

Example

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

minimum(expression)

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

Signature:

export declare function minimum(expression: Expression): AggregateFunction;

Parameters

Parameter Type Description
expression Expression The expression to find the minimum value of.

Returns:

AggregateFunction

A new AggregateFunction representing the 'minimum' aggregation.

Example

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

mod(expression, value)

Creates an expression that calculates the modulo (remainder) of dividing an expression by a constant.

Signature:

export declare function mod(expression: Expression, value: unknown): FunctionExpression;

Parameters

Parameter Type Description
expression Expression The dividend expression.
value unknown The divisor constant.

Returns:

FunctionExpression

A new Expression representing the modulo operation.

Example

// Calculate the remainder of dividing 'field1' by 5.
mod(field("field1"), 5);

notEqual(expression, value)

Creates an expression that checks if an expression is not equal to a constant value.

Signature:

export declare function notEqual(expression: Expression, value: unknown): BooleanExpression;

Parameters

Parameter Type Description
expression Expression The expression to compare.
value unknown The constant value to compare to.

Returns:

BooleanExpression

A new Expression representing the inequality comparison.

Example

// Check if the 'status' field is not equal to "completed"
notEqual(field("status"), "completed");

round(expression)

Creates an expression that rounds a numeric value to the nearest whole number.

Signature:

export declare function round(expression: Expression): FunctionExpression;

Parameters

Parameter Type Description
expression Expression An expression evaluating to a numeric value, which will be rounded.

Returns:

FunctionExpression

A new Expression representing the rounded value.

Example

// Round the value of the 'price' field.
round(field("price"));

round(expression, decimalPlaces)

Creates an expression that rounds a numeric value to the specified number of decimal places.

Signature:

export declare function round(expression: Expression, decimalPlaces: number | Expression): FunctionExpression;

Parameters

Parameter Type Description
expression Expression An expression evaluating to a numeric value, which will be rounded.
decimalPlaces number | Expression A constant or expression specifying the rounding precision in decimal places.

Returns:

FunctionExpression

A new Expression representing the rounded value.

Example

// Round the value of the 'price' field to two decimal places.
round(field("price"), constant(2));

rtrim(expression, valueToTrim)

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

Signature:

export declare function rtrim(expression: Expression, valueToTrim?: string | Expression | Bytes): FunctionExpression;

Parameters

Parameter Type Description
expression Expression The expression representing the string or byte array.
valueToTrim string | Expression | Bytes Optional. A string or byte array containing the characters/bytes to trim. If not specified, whitespace will be trimmed.

Returns:

FunctionExpression

A new Expression representing the trimmed string or byte array.

Example

// Trim whitespace from the end of the 'userInput' field
rtrim(field("userInput"));

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

split(expression, delimiter)

Creates an expression that splits a string into an array of substrings based on the provided delimiter.

Signature:

export declare function split(expression: Expression, delimiter: string): FunctionExpression;

Parameters

Parameter Type Description
expression Expression Split the result of this expression.
delimiter string Split on this delimiter.

Returns:

FunctionExpression

A new Expression representing the split function.

Example

// Split the 'scoresCsv' field on delimiter ','
split(field('scoresCsv'), ',')

split(expression, delimiter)

Creates an expression that splits a string into an array of substrings based on the provided delimiter.

Signature:

export declare function split(expression: Expression, delimiter: Expression): FunctionExpression;

Parameters

Parameter Type Description
expression Expression Split the result of this expression.
delimiter Expression Split on this delimiter returned by evaluating this expression.

Returns:

FunctionExpression

A new Expression representing the split function.

Example

// Split the 'scores' field on delimiter ',' or ':' depending on the stored format
split(field('scores'), conditional(field('format').equal('csv'), constant(','), constant(':')))

sqrt(expression)

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

Signature:

export declare function sqrt(expression: Expression): FunctionExpression;

Parameters

Parameter Type Description
expression Expression An expression evaluating to a numeric value, which the square root will be computed for.

Returns:

FunctionExpression

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

Example

// Compute the square root of the 'value' field.
sqrt(field("value"));

stringIndexOf(expression, search)

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

Signature:

export declare function stringIndexOf(expression: Expression, search: string | Expression | Bytes): FunctionExpression;

Parameters

Parameter Type Description
expression Expression The expression representing the string or byte array.
search string | Expression | Bytes The substring or byte sequence to search for.

Returns:

FunctionExpression

A new Expression representing the index of the first occurrence.

Example

// Find the index of "foo" in the 'text' field
stringIndexOf(field("text"), "foo");

stringRepeat(expression, repetitions)

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

Signature:

export declare function stringRepeat(expression: Expression, repetitions: number | Expression): FunctionExpression;

Parameters

Parameter Type Description
expression Expression The expression representing the string or byte array.
repetitions number | Expression The number of times to repeat the string or byte array.

Returns:

FunctionExpression

A new Expression representing the repeated string or byte array.

Example

// Repeat the 'label' field 3 times
stringRepeat(field("label"), 3);

stringReplaceAll(expression, find, replacement)

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

Signature:

export declare function stringReplaceAll(expression: Expression, find: string | Expression | Bytes, replacement: string | Expression | Bytes): FunctionExpression;

Parameters

Parameter Type Description
expression Expression The expression representing the string or byte array.
find string | Expression | Bytes The substring or byte sequence to search for.
replacement string | Expression | Bytes The replacement string or byte sequence.

Returns:

FunctionExpression

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

Example

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

stringReplaceOne(expression, find, replacement)

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

Signature:

export declare function stringReplaceOne(expression: Expression, find: string | Expression | Bytes, replacement: string | Expression | Bytes): FunctionExpression;

Parameters

Parameter Type Description
expression Expression The expression representing the string or byte array.
find string | Expression | Bytes The substring or byte sequence to search for.
replacement string | Expression | Bytes The replacement string or byte sequence.

Returns:

FunctionExpression

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

Example

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

subtract(expression, value)

Creates an expression that subtracts a constant value from an expression.

Signature:

export declare function subtract(expression: Expression, value: unknown): FunctionExpression;

Parameters

Parameter Type Description
expression Expression The expression to subtract from.
value unknown The constant value to subtract.

Returns:

FunctionExpression

A new Expression representing the subtraction operation.

Example

// Subtract the constant value 2 from the 'value' field
subtract(field("value"), 2);

sum(expression)

Creates an aggregation that calculates the sum of values from an expression across multiple stage inputs.

Signature:

export declare function sum(expression: Expression): AggregateFunction;

Parameters

Parameter Type Description
expression Expression The expression to sum up.

Returns:

AggregateFunction

A new AggregateFunction representing the 'sum' aggregation.

Example

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

trunc(expression)

Creates an expression that truncates the numeric value of an expression to an integer.

Signature:

export declare function trunc(expression: Expression): FunctionExpression;

Parameters

Parameter Type Description
expression Expression An expression evaluating to a numeric value, which will be truncated.

Returns:

FunctionExpression

A new Expression representing the truncated value.

Example

// Truncate the value of the 'rating' field.
trunc(field("rating"));

trunc(expression, decimalPlaces)

Creates an expression that truncates a numeric value to the specified number of decimal places.

Signature:

export declare function trunc(expression: Expression, decimalPlaces: number | Expression): FunctionExpression;

Parameters

Parameter Type Description
expression Expression An expression evaluating to a numeric value, which will be truncated.
decimalPlaces number | Expression A constant or expression specifying the truncation precision in decimal places.

Returns:

FunctionExpression

A new Expression representing the truncated value.

Example

// Truncate the value of the 'rating' field to two decimal places.
trunc(field("rating"), constant(2));

type(expression)

Creates an expression that returns the data type of an expression's result.

Signature:

export declare function type(expression: Expression): FunctionExpression;

Parameters

Parameter Type Description
expression Expression

Returns:

FunctionExpression

A new Expression representing the data type.

Example

// Get the data type of a conditional expression
type(conditional(exists('foo'), constant(1), constant(true)))

function(field, ...)

isAbsent(field)

Creates an expression that returns true if a field is absent. Otherwise, returns false even if the field value is null.

Signature:

export declare function isAbsent(field: string): BooleanExpression;

Parameters

Parameter Type Description
field string The field to check.

Returns:

BooleanExpression

A new Expression representing the 'isAbsent' check.

Example

// Check if the field `value` is absent.
isAbsent("value");

reverse(field)

Creates an expression that reverses a string value in the specified field.

Signature:

export declare function reverse(field: string): FunctionExpression;

Parameters

Parameter Type Description
field string The name of the field representing the string to reverse.

Returns:

FunctionExpression

A new Expression representing the reversed string.

Example

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

stringReverse(field)

Creates an expression that reverses a string value in the specified field.

Signature:

export declare function stringReverse(field: string): FunctionExpression;

Parameters

Parameter Type Description
field string The name of the field representing the string to reverse.

Returns:

FunctionExpression

A new Expression representing the reversed string.

Example

// Reverse the value of the 'myString' field.
stringReverse("myString");

substring(field, position, length)

Creates an expression that returns a substring of a string or byte array.

Signature:

export declare function substring(field: string, position: number, length?: number): FunctionExpression;

Parameters

Parameter Type Description
field string The name of a field containing a string or byte array to compute the substring from.
position number Index of the first character of the substring.
length number Length of the substring.

Returns:

FunctionExpression

substring(field, position, length)

Creates an expression that returns a substring of a string or byte array.

Signature:

export declare function substring(field: string, position: Expression, length?: Expression): FunctionExpression;

Parameters

Parameter Type Description
field string The name of a field containing a string or byte array to compute the substring from.
position Expression An expression that returns the index of the first character of the substring.
length Expression An expression that returns the length of the substring.

Returns:

FunctionExpression

function(fieldName, ...)

abs(fieldName)

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

Signature:

export declare function abs(fieldName: string): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The field to compute the absolute value of.

Returns:

FunctionExpression

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

add(fieldName, second)

Creates an expression that adds a field's value to an expression.

Signature:

export declare function add(fieldName: string, second: Expression | unknown): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field containing the value to add.
second Expression | unknown The second expression or literal to add.

Returns:

FunctionExpression

A new Expression representing the addition operation.

Example

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

arrayAgg(fieldName)

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

If the expression resolves to an absent value, it is converted to null. The order of elements in the output array is not stable and shouldn't be relied upon.

Signature:

export declare function arrayAgg(fieldName: string): AggregateFunction;

Parameters

Parameter Type Description
fieldName string The name of the field to collect values from.

Returns:

AggregateFunction

A new AggregateFunction representing the 'array_agg' aggregation.

Example

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

arrayAggDistinct(fieldName)

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

If the expression resolves to an absent value, it is converted to null. The order of elements in the output array is not stable and shouldn't be relied upon.

Signature:

export declare function arrayAggDistinct(fieldName: string): AggregateFunction;

Parameters

Parameter Type Description
fieldName string The name of the field to collect values from.

Returns:

AggregateFunction

A new AggregateFunction representing the 'array_agg_distinct' aggregation.

Example

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

arrayContains(fieldName, element)

Creates an expression that checks if a field's array value contains a specific element.

Signature:

export declare function arrayContains(fieldName: string, element: Expression): BooleanExpression;

Parameters

Parameter Type Description
fieldName string The field name to check.
element Expression The element to search for in the array.

Returns:

BooleanExpression

A new Expression representing the 'array_contains' comparison.

Example

// Check if the 'colors' array contains the value of field 'selectedColor'
arrayContains("colors", field("selectedColor"));

arrayContains(fieldName, element)

Creates an expression that checks if a field's array value contains a specific value.

Signature:

export declare function arrayContains(fieldName: string, element: unknown): BooleanExpression;

Parameters

Parameter Type Description
fieldName string The field name to check.
element unknown The element to search for in the array.

Returns:

BooleanExpression

A new Expression representing the 'array_contains' comparison.

Example

// Check if the 'colors' array contains "red"
arrayContains("colors", "red");

arrayContainsAll(fieldName, values)

Creates an expression that checks if a field's array value contains all the specified values or expressions.

Signature:

export declare function arrayContainsAll(fieldName: string, values: Array<Expression | unknown>): BooleanExpression;

Parameters

Parameter Type Description
fieldName string The field name to check.
values Array<Expression | unknown> The elements to check for in the array.

Returns:

BooleanExpression

A new Expression representing the 'array_contains_all' comparison.

Example

// Check if the 'tags' array contains both of the values from field 'tag1', the value "SciFi", and "Adventure"
arrayContainsAll("tags", [field("tag1"), "SciFi", "Adventure"]);

arrayContainsAll(fieldName, arrayExpression)

Creates an expression that checks if a field's array value contains all the specified values or expressions.

Signature:

export declare function arrayContainsAll(fieldName: string, arrayExpression: Expression): BooleanExpression;

Parameters

Parameter Type Description
fieldName string The field name to check.
arrayExpression Expression The elements to check for in the array.

Returns:

BooleanExpression

A new Expression representing the 'array_contains_all' comparison.

Example

// Check if the 'tags' array contains both of the values from field 'tag1', the value "SciFi", and "Adventure"
arrayContainsAll("tags", [field("tag1"), "SciFi", "Adventure"]);

arrayContainsAny(fieldName, values)

Creates an expression that checks if a field's array value contains any of the specified elements.

Signature:

export declare function arrayContainsAny(fieldName: string, values: Array<Expression | unknown>): BooleanExpression;

Parameters

Parameter Type Description
fieldName string The field name to check.
values Array<Expression | unknown> The elements to check for in the array.

Returns:

BooleanExpression

A new Expression representing the 'array_contains_any' comparison.

Example

// Check if the 'groups' array contains either the value from the 'userGroup' field
// or the value "guest"
arrayContainsAny("categories", [field("cate1"), "Science"]);

arrayContainsAny(fieldName, values)

Creates an expression that checks if a field's array value contains any of the specified elements.

Signature:

export declare function arrayContainsAny(fieldName: string, values: Expression): BooleanExpression;

Parameters

Parameter Type Description
fieldName string The field name to check.
values Expression An expression that evaluates to an array, whose elements to check for in the array field.

Returns:

BooleanExpression

A new Expression representing the 'array_contains_any' comparison.

Example

// Check if the 'groups' array contains either the value from the 'userGroup' field
// or the value "guest"
arrayContainsAny("categories", array([field("cate1"), "Science"]));

arrayFilter(fieldName, alias, filter)

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

Signature:

export declare function arrayFilter(fieldName: string, alias: string, filter: BooleanExpression): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field containing the array.
alias string The variable name to use for each element.
filter BooleanExpression The predicate boolean expression to evaluate for each element.

Returns:

FunctionExpression

A new Expression representing the filtered array.

Example

// Get a filtered array of the 'scores' field containing only elements greater than 50.
arrayFilter("scores", "score", greaterThan(variable("score"), 50));

arrayFirst(fieldName)

Creates an expression that returns the first element of an array.

Signature:

export declare function arrayFirst(fieldName: string): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field containing the array.

Returns:

FunctionExpression

A new Expression representing the first element.

Example

// Get the first tag from the 'tags' array field
arrayFirst("tags");

arrayFirstN(fieldName, n)

Creates an expression that returns the first n elements of an array.

Signature:

export declare function arrayFirstN(fieldName: string, n: number): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field containing the array.
n number The number of elements to return.

Returns:

FunctionExpression

A new Expression representing the first n elements.

Example

// Get the first 3 tags from the 'tags' array field
arrayFirstN("tags", 3);

arrayFirstN(fieldName, n)

Creates an expression that returns the first n elements of an array.

Signature:

export declare function arrayFirstN(fieldName: string, n: Expression): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field containing the array.
n Expression An expression evaluating to the number of elements to return.

Returns:

FunctionExpression

A new Expression representing the first n elements.

Example

// Get the first n tags from the 'tags' array field
arrayFirstN("tags", field("count"));

arrayIndexOf(fieldName, search)

Creates an expression that returns the first index of the search value in an array. Returns -1 if the value is not found.

Signature:

export declare function arrayIndexOf(fieldName: string, search: unknown | Expression): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field containing the array to search.
search unknown | Expression The value to search for.

Returns:

FunctionExpression

A new Expression representing the index.

Example

// Get the index of "politics" in the 'tags' array field
arrayIndexOf("tags", "politics");

arrayIndexOfAll(fieldName, search)

Creates an expression that returns all indices of the search value in an array.

Signature:

export declare function arrayIndexOfAll(fieldName: string, search: unknown | Expression): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field containing the array to search.
search unknown | Expression The value to search for.

Returns:

FunctionExpression

A new Expression representing the indices.

Example

// Get all indices of 5 in the 'scores' array field
arrayIndexOfAll("scores", 5);

arrayLast(fieldName)

Creates an expression that returns the last element of an array.

Signature:

export declare function arrayLast(fieldName: string): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field containing the array.

Returns:

FunctionExpression

A new Expression representing the last element.

Example

// Get the last tag from the 'tags' array field
arrayLast("tags");

arrayLastIndexOf(fieldName, search)

Creates an expression that returns the last index of the search value in an array. Returns -1 if the value is not found.

Signature:

export declare function arrayLastIndexOf(fieldName: string, search: unknown | Expression): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field containing the array to search.
search unknown | Expression The value to search for.

Returns:

FunctionExpression

A new Expression representing the index.

Example

// Get the last index of "politics" in the 'tags' array field
arrayLastIndexOf("tags", "politics");

arrayLastN(fieldName, n)

Creates an expression that returns the last n elements of an array.

Signature:

export declare function arrayLastN(fieldName: string, n: number): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field containing the array.
n number The number of elements to return.

Returns:

FunctionExpression

A new Expression representing the last n elements.

Example

// Get the last 3 tags from the 'tags' array field
arrayLastN("tags", 3);

arrayLastN(fieldName, n)

Creates an expression that returns the last n elements of an array.

Signature:

export declare function arrayLastN(fieldName: string, n: Expression): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field containing the array.
n Expression An expression evaluating to the number of elements to return.

Returns:

FunctionExpression

A new Expression representing the last n elements.

Example

// Get the last n tags from the 'tags' array field
arrayLastN("tags", field("count"));

arrayLength(fieldName)

Creates an expression that calculates the length of an array in a specified field.

Signature:

export declare function arrayLength(fieldName: string): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field containing an array to calculate the length of.

Returns:

FunctionExpression

A new Expression representing the length of the array.

Example

// Get the number of items in field 'cart'
arrayLength('cart');

arrayMaximum(fieldName)

Creates an expression that returns the maximum value in an array.

Signature:

export declare function arrayMaximum(fieldName: string): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field containing the array.

Returns:

FunctionExpression

A new Expression representing the maximum value.

Example

// Get the maximum value from the 'scores' array field
arrayMaximum("scores");

arrayMaximumN(fieldName, n)

Creates an expression that returns the largest n elements of an array.

Signature:

export declare function arrayMaximumN(fieldName: string, n: number): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field containing the array.
n number The number of elements to return.

Returns:

FunctionExpression

A new Expression representing the largest n elements.

Example

// Get the top 3 scores from the 'scores' array field
arrayMaximumN("scores", 3);

arrayMaximumN(fieldName, n)

Creates an expression that returns the largest n elements of an array.

Signature:

export declare function arrayMaximumN(fieldName: string, n: Expression): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field containing the array.
n Expression An expression evaluating to the number of elements to return.

Returns:

FunctionExpression

A new Expression representing the largest n elements.

Example

// Get the top n scores from the 'scores' array field
arrayMaximumN("scores", field("count"));

arrayMinimum(fieldName)

Creates an expression that returns the minimum value in an array.

Signature:

export declare function arrayMinimum(fieldName: string): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field containing the array.

Returns:

FunctionExpression

A new Expression representing the minimum value.

Example

// Get the minimum value from the 'scores' array field
arrayMinimum("scores");

arrayMinimumN(fieldName, n)

Creates an expression that returns the smallest n elements of an array.

Signature:

export declare function arrayMinimumN(fieldName: string, n: number): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field containing the array.
n number The number of elements to return.

Returns:

FunctionExpression

A new Expression representing the smallest n elements.

Example

// Get the bottom 3 scores from the 'scores' array field
arrayMinimumN("scores", 3);

arrayMinimumN(fieldName, n)

Creates an expression that returns the smallest n elements of an array.

Signature:

export declare function arrayMinimumN(fieldName: string, n: Expression): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field containing the array.
n Expression An expression evaluating to the number of elements to return.

Returns:

FunctionExpression

A new Expression representing the smallest n elements.

Example

// Get the bottom n scores from the 'scores' array field
arrayMinimumN(field("scores"), field("count"));

arraySlice(fieldName, offset, length)

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

Signature:

export declare function arraySlice(fieldName: string, offset: number | Expression, length?: number | Expression): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field containing the array.
offset number | Expression The starting offset.
length number | Expression The optional length of the slice.

Returns:

FunctionExpression

A new Expression representing the sliced array.

Example

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

// Get n elements from the 'items' array field starting from index 2
arraySlice("items", 2, field("length"));

arraySum(fieldName)

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

Signature:

export declare function arraySum(fieldName: string): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field to compute the sum of.

Returns:

FunctionExpression

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

Example

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

arrayTransform(fieldName, elementAlias, transform)

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

Signature:

export declare function arrayTransform(fieldName: string, elementAlias: string, transform: Expression): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field containing the array.
elementAlias string The variable name to use for each element.
transform Expression The expression used to transform the elements.

Returns:

FunctionExpression

A new Expression representing the transformed array.

Example

// Transform "scores" array by multiplying each score by 10
arrayTransform("scores", "score", multiply(variable("score"), 10));

arrayTransformWithIndex(fieldName, 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.

Signature:

export declare function arrayTransformWithIndex(fieldName: string, elementAlias: string, indexAlias: string, transform: Expression): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field containing the array.
elementAlias string The variable name to use for each element.
indexAlias string The variable name to use for the current index.
transform Expression The lambda expression used to transform the elements.

Returns:

FunctionExpression

A new Expression representing the transformed array.

Example

// Transform "scores" array by adding the index to each score
arrayTransformWithIndex("scores", "score", "i", add(variable("score"), variable("i")));

ascending(fieldName)

Creates an Ordering that sorts documents in ascending order based on a field.

Signature:

export declare function ascending(fieldName: string): Ordering;

Parameters

Parameter Type Description
fieldName string The field to create an ascending ordering for.

Returns:

Ordering

A new Ordering for ascending sorting.

Example

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

average(fieldName)

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

Signature:

export declare function average(fieldName: string): AggregateFunction;

Parameters

Parameter Type Description
fieldName string The name of the field containing numeric values to average.

Returns:

AggregateFunction

A new AggregateFunction representing the 'average' aggregation.

Example

// Calculate the average age of users
average("age").as("averageAge");

byteLength(fieldName)

Creates an expression that calculates the length of a string represented by a field in UTF-8 bytes, or just the length of a Blob.

Signature:

export declare function byteLength(fieldName: string): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field containing the string.

Returns:

FunctionExpression

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

Example

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

ceil(fieldName)

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

Signature:

export declare function ceil(fieldName: string): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field to compute the ceiling of.

Returns:

FunctionExpression

A new Expression representing the ceiling of the numeric value.

Example

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

charLength(fieldName)

Creates an expression that calculates the character length of a string field in UTF8.

Signature:

export declare function charLength(fieldName: string): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field containing the string.

Returns:

FunctionExpression

A new Expression representing the length of the string.

Example

// Get the character length of the 'name' field in UTF-8.
charLength("name");

coalesce(fieldName, 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.

Signature:

export declare function coalesce(fieldName: string, replacement: Expression | unknown, ...others: Array<Expression | unknown>): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the first field to check for null.
replacement Expression | unknown The fallback expression or value if the first one is null.
others Array<Expression | unknown> Optional additional expressions to check if previous ones are null.

Returns:

FunctionExpression

A new Expression representing the coalesce operation.

Example

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

collectionId(fieldName)

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

Signature:

export declare function collectionId(fieldName: string): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field to get the collection ID from.

Returns:

FunctionExpression

A new Expression representing the collectionId operation.

Example

// Get the collection ID from a path.
collectionId("__name__");

concat(fieldName, second, others)

Creates an expression that concatenates strings, arrays, or blobs. Types cannot be mixed.

Signature:

export declare function concat(fieldName: string, second: Expression | unknown, ...others: Array<Expression | unknown>): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of a field to concatenate.
second Expression | unknown The second literal or expression to concatenate.
others Array<Expression | unknown> Additional literal or expressions to concatenate.

Returns:

FunctionExpression

A new Expression representing the concatenation.

Example

// Concatenate a field with a literal string.
concat(field("firstName"), "Doe")

cosineDistance(fieldName, vector)

Calculates the Cosine distance between a field's vector value and a literal vector value.

Signature:

export declare function cosineDistance(fieldName: string, vector: number[] | VectorValue): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field containing the first vector.
vector number[] | VectorValue The other vector (as an array of doubles) or VectorValue to compare against.

Returns:

FunctionExpression

A new Expression representing the Cosine distance between the two vectors.

Example

// Calculate the Cosine distance between the 'location' field and a target location
cosineDistance("location", [37.7749, -122.4194]);

cosineDistance(fieldName, vectorExpression)

Calculates the Cosine distance between a field's vector value and a vector expression.

Signature:

export declare function cosineDistance(fieldName: string, vectorExpression: Expression): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field containing the first vector.
vectorExpression Expression The other vector (represented as an Expression) to compare against.

Returns:

FunctionExpression

A new Expression representing the cosine distance between the two vectors.

Example

// Calculate the cosine distance between the 'userVector' field and the 'itemVector' field
cosineDistance("userVector", field("itemVector"));

count(fieldName)

Creates an aggregation that counts the number of stage inputs where the input field exists.

Signature:

export declare function count(fieldName: string): AggregateFunction;

Parameters

Parameter Type Description
fieldName string The name of the field to count.

Returns:

AggregateFunction

A new AggregateFunction representing the 'count' aggregation.

Example

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

descending(fieldName)

Creates an Ordering that sorts documents in descending order based on a field.

Signature:

export declare function descending(fieldName: string): Ordering;

Parameters

Parameter Type Description
fieldName string The field to create a descending ordering for.

Returns:

Ordering

A new Ordering for descending sorting.

Example

// Sort documents by the 'name' field in descending order
firestore.pipeline().collection("users")
  .sort(descending("name"));

divide(fieldName, expressions)

Creates an expression that divides a field's value by an expression.

Signature:

export declare function divide(fieldName: string, expressions: Expression): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The field name to be divided.
expressions Expression The expression to divide by.

Returns:

FunctionExpression

A new Expression representing the division operation.

Example

// Divide the 'total' field by the 'count' field
divide("total", field("count"));

divide(fieldName, value)

Creates an expression that divides a field's value by a constant value.

Signature:

export declare function divide(fieldName: string, value: unknown): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The field name to be divided.
value unknown The constant value to divide by.

Returns:

FunctionExpression

A new Expression representing the division operation.

Example

// Divide the 'value' field by 10
divide("value", 10);

dotProduct(fieldName, vector)

Calculates the dot product between a field's vector value and a double array.

Signature:

export declare function dotProduct(fieldName: string, vector: number[] | VectorValue): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field containing the first vector.
vector number[] | VectorValue The other vector (as an array of doubles or VectorValue) to calculate with.

Returns:

FunctionExpression

A new Expression representing the dot product between the two vectors.

Example

// Calculate the dot product distance between a feature vector and a target vector
dotProduct("features", [0.5, 0.8, 0.2]);

dotProduct(fieldName, vectorExpression)

Calculates the dot product between a field's vector value and a vector expression.

Signature:

export declare function dotProduct(fieldName: string, vectorExpression: Expression): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field containing the first vector.
vectorExpression Expression The other vector (represented as an Expression) to calculate with.

Returns:

FunctionExpression

A new Expression representing the dot product between the two vectors.

Example

// Calculate the dot product distance between two document vectors: 'docVector1' and 'docVector2'
dotProduct("docVector1", field("docVector2"));

endsWith(fieldName, suffix)

Creates an expression that checks if a field's value ends with a given postfix.

Signature:

export declare function endsWith(fieldName: string, suffix: string): BooleanExpression;

Parameters

Parameter Type Description
fieldName string The field name to check.
suffix string The postfix to check for.

Returns:

BooleanExpression

A new Expression representing the 'ends with' comparison.

Example

// Check if the 'filename' field ends with ".txt"
endsWith("filename", ".txt");

endsWith(fieldName, suffix)

Creates an expression that checks if a field's value ends with a given postfix.

Signature:

export declare function endsWith(fieldName: string, suffix: Expression): BooleanExpression;

Parameters

Parameter Type Description
fieldName string The field name to check.
suffix Expression The expression representing the postfix.

Returns:

BooleanExpression

A new Expression representing the 'ends with' comparison.

Example

// Check if the 'url' field ends with the value of the 'extension' field
endsWith("url", field("extension"));

equal(fieldName, expression)

Creates an expression that checks if a field's value is equal to an expression.

Signature:

export declare function equal(fieldName: string, expression: Expression): BooleanExpression;

Parameters

Parameter Type Description
fieldName string The field name to compare.
expression Expression The expression to compare to.

Returns:

BooleanExpression

A new Expression representing the equality comparison.

Example

// Check if the 'age' field is equal to the 'limit' field
equal("age", field("limit"));

equal(fieldName, value)

Creates an expression that checks if a field's value is equal to a constant value.

Signature:

export declare function equal(fieldName: string, value: unknown): BooleanExpression;

Parameters

Parameter Type Description
fieldName string The field name to compare.
value unknown The constant value to compare to.

Returns:

BooleanExpression

A new Expression representing the equality comparison.

Example

// Check if the 'city' field is equal to string constant "London"
equal("city", "London");

equalAny(fieldName, values)

Creates an expression that checks if a field's value is equal to any of the provided values or expressions.

Signature:

export declare function equalAny(fieldName: string, values: Array<Expression | unknown>): BooleanExpression;

Parameters

Parameter Type Description
fieldName string The field to compare.
values Array<Expression | unknown> The values to check against.

Returns:

BooleanExpression

A new Expression representing the 'IN' comparison.

Example

// Check if the 'category' field is either "Electronics" or value of field 'primaryType'
equalAny("category", [constant("Electronics"), field("primaryType")]);

equalAny(fieldName, arrayExpression)

Creates an expression that checks if a field's value is equal to any of the provided values or expressions.

Signature:

export declare function equalAny(fieldName: string, arrayExpression: Expression): BooleanExpression;

Parameters

Parameter Type Description
fieldName string The field to compare.
arrayExpression Expression An expression that evaluates to an array, whose elements to check for equality to the input field.

Returns:

BooleanExpression

A new Expression representing the 'IN' comparison.

Example

// Check if the 'category' field is either "Electronics" or value of field 'primaryType'
equalAny("category", ["Electronics", field("primaryType")]);

euclideanDistance(fieldName, vector)

Calculates the Euclidean distance between a field's vector value and a double array.

Signature:

export declare function euclideanDistance(fieldName: string, vector: number[] | VectorValue): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field containing the first vector.
vector number[] | VectorValue The other vector (as an array of doubles or VectorValue) to compare against.

Returns:

FunctionExpression

A new Expression representing the Euclidean distance between the two vectors.

Example

// Calculate the Euclidean distance between the 'location' field and a target location
euclideanDistance("location", [37.7749, -122.4194]);

euclideanDistance(fieldName, vectorExpression)

Calculates the Euclidean distance between a field's vector value and a vector expression.

Signature:

export declare function euclideanDistance(fieldName: string, vectorExpression: Expression): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field containing the first vector.
vectorExpression Expression The other vector (represented as an Expression) to compare against.

Returns:

FunctionExpression

A new Expression representing the Euclidean distance between the two vectors.

Example

// Calculate the Euclidean distance between two vector fields: 'pointA' and 'pointB'
euclideanDistance("pointA", field("pointB"));

exists(fieldName)

Creates an expression that checks if a field exists.

Signature:

export declare function exists(fieldName: string): BooleanExpression;

Parameters

Parameter Type Description
fieldName string The field name to check.

Returns:

BooleanExpression

A new Expression representing the 'exists' check.

Example

// Check if the document has a field named "phoneNumber"
exists("phoneNumber");

exp(fieldName)

Creates an expression that computes e to the power of the expression's result.

Signature:

export declare function exp(fieldName: string): FunctionExpression;

Parameters

Parameter Type Description
fieldName string

Returns:

FunctionExpression

A new Expression representing the exp of the numeric value.

Example

// Compute e to the power of the 'value' field.
exp('value');

first(fieldName)

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

Signature:

export declare function first(fieldName: string): AggregateFunction;

Parameters

Parameter Type Description
fieldName string The name of the field to find the first value of.

Returns:

AggregateFunction

A new AggregateFunction representing the 'first' aggregation.

Example

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

floor(fieldName)

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

Signature:

export declare function floor(fieldName: string): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field to compute the floor of.

Returns:

FunctionExpression

A new Expression representing the floor of the numeric value.

geoDistance(fieldName, location)

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

Evaluates to the distance in meters between the location in the specified field and the query location.

This Expression can only be used within a Search stage.

Signature:

export declare function geoDistance(fieldName: string | Field, location: GeoPoint | Expression): Expression;

Parameters

Parameter Type Description
fieldName string | Field Specifies the field in the document which contains the first GeoPoint for distance computation.
location GeoPoint | Expression Compute distance to this GeoPoint.

Returns:

Expression

Example

db.pipeline().collection('restaurants').search({
  query: 'waffles',
  sort: geoDistance('location', new GeoPoint(37.0, -122.0)).ascending()
})

greaterThan(fieldName, expression)

Creates an expression that checks if a field's value is greater than an expression.

Signature:

export declare function greaterThan(fieldName: string, expression: Expression): BooleanExpression;

Parameters

Parameter Type Description
fieldName string The field name to compare.
expression Expression The expression to compare to.

Returns:

BooleanExpression

A new Expression representing the greater than comparison.

Example

// Check if the value of field 'age' is greater than the value of field 'limit'
greaterThan("age", field("limit"));

greaterThan(fieldName, value)

Creates an expression that checks if a field's value is greater than a constant value.

Signature:

export declare function greaterThan(fieldName: string, value: unknown): BooleanExpression;

Parameters

Parameter Type Description
fieldName string The field name to compare.
value unknown The constant value to compare to.

Returns:

BooleanExpression

A new Expression representing the greater than comparison.

Example

// Check if the 'price' field is greater than 100
greaterThan("price", 100);

greaterThanOrEqual(fieldName, value)

Creates an expression that checks if a field's value is greater than or equal to an expression.

Signature:

export declare function greaterThanOrEqual(fieldName: string, value: Expression): BooleanExpression;

Parameters

Parameter Type Description
fieldName string The field name to compare.
value Expression The expression to compare to.

Returns:

BooleanExpression

A new Expression representing the greater than or equal to comparison.

Example

// Check if the value of field 'age' is greater than or equal to the value of field 'limit'
greaterThanOrEqual("age", field("limit"));

greaterThanOrEqual(fieldName, value)

Creates an expression that checks if a field's value is greater than or equal to a constant value.

Signature:

export declare function greaterThanOrEqual(fieldName: string, value: unknown): BooleanExpression;

Parameters

Parameter Type Description
fieldName string The field name to compare.
value unknown The constant value to compare to.

Returns:

BooleanExpression

A new Expression representing the greater than or equal to comparison.

Example

// Check if the 'score' field is greater than or equal to 80
greaterThanOrEqual("score", 80);

isType(fieldName, type)

Creates an expression that checks if the value in the specified field is of the given type.

Null or undefined fields evaluate to skip/error. Use ifAbsent() / isAbsent() to evaluate missing data. Supported values for type are: 'null', 'array', 'boolean', 'bytes', 'timestamp', 'geo_point', 'number', 'int32', 'int64', 'float64', 'decimal128', 'map', 'reference', 'string', 'vector', 'max_key', 'min_key', 'object_id', 'regex', 'request_timestamp'.

Signature:

export declare function isType(fieldName: string, type: string): BooleanExpression;

Parameters

Parameter Type Description
fieldName string The name of the field to check.
type string The type to check for.

Returns:

BooleanExpression

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

Example

// Check if the 'price' field is a floating point number (evaluating to true inside pipeline conditionals)
isType('price', 'float64');

last(fieldName)

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

Signature:

export declare function last(fieldName: string): AggregateFunction;

Parameters

Parameter Type Description
fieldName string The name of the field to find the last value of.

Returns:

AggregateFunction

A new AggregateFunction representing the 'last' aggregation.

Example

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

length_2(fieldName)

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

Signature:

declare function length_2(fieldName: string): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field to calculate the length of.

Returns:

FunctionExpression

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

Example

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

// Get the number of items in the 'cart' array.
length("cart");

lessThan(fieldName, expression)

Creates an expression that checks if a field's value is less than an expression.

Signature:

export declare function lessThan(fieldName: string, expression: Expression): BooleanExpression;

Parameters

Parameter Type Description
fieldName string The field name to compare.
expression Expression The expression to compare to.

Returns:

BooleanExpression

A new Expression representing the less than comparison.

Example

// Check if the 'age' field is less than the 'limit' field
lessThan("age", field("limit"));

lessThan(fieldName, value)

Creates an expression that checks if a field's value is less than a constant value.

Signature:

export declare function lessThan(fieldName: string, value: unknown): BooleanExpression;

Parameters

Parameter Type Description
fieldName string The field name to compare.
value unknown The constant value to compare to.

Returns:

BooleanExpression

A new Expression representing the less than comparison.

Example

// Check if the 'price' field is less than 50
lessThan("price", 50);

lessThanOrEqual(fieldName, expression)

Creates an expression that checks if a field's value is less than or equal to an expression.

Signature:

export declare function lessThanOrEqual(fieldName: string, expression: Expression): BooleanExpression;

Parameters

Parameter Type Description
fieldName string The field name to compare.
expression Expression The expression to compare to.

Returns:

BooleanExpression

A new Expression representing the less than or equal to comparison.

Example

// Check if the 'quantity' field is less than or equal to the 'limit' field
lessThan("quantity", field("limit"));

lessThanOrEqual(fieldName, value)

Creates an expression that checks if a field's value is less than or equal to a constant value.

Signature:

export declare function lessThanOrEqual(fieldName: string, value: unknown): BooleanExpression;

Parameters

Parameter Type Description
fieldName string The field name to compare.
value unknown The constant value to compare to.

Returns:

BooleanExpression

A new Expression representing the less than or equal to comparison.

Example

// Check if the 'score' field is less than or equal to 70
lessThan("score", 70);

like(fieldName, pattern)

Creates an expression that performs a case-sensitive wildcard string comparison against a field.

Signature:

export declare function like(fieldName: string, pattern: string): BooleanExpression;

Parameters

Parameter Type Description
fieldName string The name of the field containing the string.
pattern string The pattern to search for. You can use "%" as a wildcard character.

Returns:

BooleanExpression

A new Expression representing the 'like' comparison.

Example

// Check if the 'title' field contains the string "guide"
like("title", "%guide%");

like(fieldName, pattern)

Creates an expression that performs a case-sensitive wildcard string comparison against a field.

Signature:

export declare function like(fieldName: string, pattern: Expression): BooleanExpression;

Parameters

Parameter Type Description
fieldName string The name of the field containing the string.
pattern Expression The pattern to search for. You can use "%" as a wildcard character.

Returns:

BooleanExpression

A new Expression representing the 'like' comparison.

Example

// Check if the 'title' field contains the string "guide"
like("title", field("pattern"));

ln(fieldName)

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

Signature:

export declare function ln(fieldName: string): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field to compute the natural logarithm of.

Returns:

FunctionExpression

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

Example

// Compute the natural logarithm of the 'value' field.
ln("value");

log(fieldName, base)

Creates an expression that computes the logarithm of a field to a given base.

Signature:

export declare function log(fieldName: string, base: number): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field to compute the logarithm of.
base number The base of the logarithm.

Returns:

FunctionExpression

A new Expression representing the logarithm of the numeric value.

Example

// Compute the logarithm of the 'value' field with base 10.
log("value", 10);

log(fieldName, base)

Creates an expression that computes the logarithm of a field to a given base.

Signature:

export declare function log(fieldName: string, base: Expression): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field to compute the logarithm of.
base Expression The base of the logarithm.

Returns:

FunctionExpression

A new Expression representing the logarithm of the numeric value.

Example

// Compute the logarithm of the 'value' field with the base in the 'base' field.
log("value", field("base"));

log10(fieldName)

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

Signature:

export declare function log10(fieldName: string): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field to compute the base-10 logarithm of.

Returns:

FunctionExpression

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

Example

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

logicalMaximum(fieldName, second, others)

Creates an expression that returns the largest value between multiple input expressions or literal values. Based on Firestore's value type ordering.

Signature:

export declare function logicalMaximum(fieldName: string, second: Expression | unknown, ...others: Array<Expression | unknown>): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The first operand field name.
second Expression | unknown The second expression or literal.
others Array<Expression | unknown> Optional additional expressions or literals.

Returns:

FunctionExpression

A new Expression representing the logical maximum operation.

Example

// Returns the largest value between the 'field1' field, the 'field2' field,
// and 1000.
logicalMaximum("field1", field("field2"), 1000);

logicalMinimum(fieldName, second, others)

Creates an expression that returns the smallest value between a field's value and other input expressions or literal values. Based on Firestore's value type ordering.

Signature:

export declare function logicalMinimum(fieldName: string, second: Expression | unknown, ...others: Array<Expression | unknown>): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The first operand field name.
second Expression | unknown The second expression or literal.
others Array<Expression | unknown> Optional additional expressions or literals.

Returns:

FunctionExpression

A new Expression representing the logical minimum operation.

Example

// Returns the smallest value between the 'field1' field, the 'field2' field,
// and 1000.
logicalMinimum("field1", field("field2"), 1000);

ltrim(fieldName, valueToTrim)

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

Signature:

export declare function ltrim(fieldName: string, valueToTrim?: string | Expression | Bytes): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field containing the string or byte array.
valueToTrim string | Expression | Bytes Optional. A string or byte array containing the characters/bytes to trim. If not specified, whitespace will be trimmed.

Returns:

FunctionExpression

A new Expression representing the trimmed string or byte array.

Example

// Trim whitespace from the beginning of the 'userInput' field
ltrim(field("userInput"));

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

mapGet(fieldName, subField)

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

Signature:

export declare function mapGet(fieldName: string, subField: string): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The field name of the map field.
subField string The key to access in the map.

Returns:

FunctionExpression

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

Example

// Get the 'city' value from the 'address' map field
mapGet("address", "city");

maximum(fieldName)

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

Signature:

export declare function maximum(fieldName: string): AggregateFunction;

Parameters

Parameter Type Description
fieldName string The name of the field to find the maximum value of.

Returns:

AggregateFunction

A new AggregateFunction representing the 'maximum' aggregation.

Example

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

minimum(fieldName)

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

Signature:

export declare function minimum(fieldName: string): AggregateFunction;

Parameters

Parameter Type Description
fieldName string The name of the field to find the minimum value of.

Returns:

AggregateFunction

A new AggregateFunction representing the 'minimum' aggregation.

Example

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

mod(fieldName, expression)

Creates an expression that calculates the modulo (remainder) of dividing a field's value by an expression.

Signature:

export declare function mod(fieldName: string, expression: Expression): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The dividend field name.
expression Expression The divisor expression.

Returns:

FunctionExpression

A new Expression representing the modulo operation.

Example

// Calculate the remainder of dividing 'field1' by 'field2'.
mod("field1", field("field2"));

mod(fieldName, value)

Creates an expression that calculates the modulo (remainder) of dividing a field's value by a constant.

Signature:

export declare function mod(fieldName: string, value: unknown): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The dividend field name.
value unknown The divisor constant.

Returns:

FunctionExpression

A new Expression representing the modulo operation.

Example

// Calculate the remainder of dividing 'field1' by 5.
mod("field1", 5);

multiply(fieldName, second)

Creates an expression that multiplies a field's value by an expression.

Signature:

export declare function multiply(fieldName: string, second: Expression | unknown): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field containing the value to add.
second Expression | unknown The second expression or literal to add.

Returns:

FunctionExpression

A new Expression representing the multiplication operation.

Example

// Multiply the 'quantity' field by the 'price' field
multiply("quantity", field("price"));

notEqual(fieldName, expression)

Creates an expression that checks if a field's value is not equal to an expression.

Signature:

export declare function notEqual(fieldName: string, expression: Expression): BooleanExpression;

Parameters

Parameter Type Description
fieldName string The field name to compare.
expression Expression The expression to compare to.

Returns:

BooleanExpression

A new Expression representing the inequality comparison.

Example

// Check if the 'status' field is not equal to the value of 'expectedStatus'
notEqual("status", field("expectedStatus"));

notEqual(fieldName, value)

Creates an expression that checks if a field's value is not equal to a constant value.

Signature:

export declare function notEqual(fieldName: string, value: unknown): BooleanExpression;

Parameters

Parameter Type Description
fieldName string The field name to compare.
value unknown The constant value to compare to.

Returns:

BooleanExpression

A new Expression representing the inequality comparison.

Example

// Check if the 'country' field is not equal to "USA"
notEqual("country", "USA");

notEqualAny(fieldName, values)

Creates an expression that checks if a field's value is not equal to any of the provided values or expressions.

Signature:

export declare function notEqualAny(fieldName: string, values: Array<Expression | unknown>): BooleanExpression;

Parameters

Parameter Type Description
fieldName string The field name to compare.
values Array<Expression | unknown> The values to check against.

Returns:

BooleanExpression

A new Expression representing the 'NOT IN' comparison.

Example

// Check if the 'status' field is neither "pending" nor the value of 'rejectedStatus'
notEqualAny("status", [constant("pending"), field("rejectedStatus")]);

notEqualAny(fieldName, arrayExpression)

Creates an expression that checks if a field's value is not equal to any of the values in the evaluated expression.

Signature:

export declare function notEqualAny(fieldName: string, arrayExpression: Expression): BooleanExpression;

Parameters

Parameter Type Description
fieldName string The field name to compare.
arrayExpression Expression The values to check against.

Returns:

BooleanExpression

A new Expression representing the 'NOT IN' comparison.

Example

// Check if the 'status' field is not equal to any value in the field 'rejectedStatuses'
notEqualAny("status", field("rejectedStatuses"));

regexContains(fieldName, pattern)

Creates an expression that checks if a string field contains a specified regular expression as a substring.

Signature:

export declare function regexContains(fieldName: string, pattern: string): BooleanExpression;

Parameters

Parameter Type Description
fieldName string The name of the field containing the string.
pattern string The regular expression to use for the search.

Returns:

BooleanExpression

A new Expression representing the 'contains' comparison.

Example

// Check if the 'description' field contains "example" (case-insensitive)
regexContains("description", "(?i)example");

regexContains(fieldName, pattern)

Creates an expression that checks if a string field contains a specified regular expression as a substring.

Signature:

export declare function regexContains(fieldName: string, pattern: Expression): BooleanExpression;

Parameters

Parameter Type Description
fieldName string The name of the field containing the string.
pattern Expression The regular expression to use for the search.

Returns:

BooleanExpression

A new Expression representing the 'contains' comparison.

Example

// Check if the 'description' field contains "example" (case-insensitive)
regexContains("description", field("pattern"));

regexFind(fieldName, pattern)

Creates an expression that returns the first substring of a string field that matches a specified regular expression.

This expression uses the RE2 regular expression syntax.

Signature:

export declare function regexFind(fieldName: string, pattern: string): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field containing the string to search.
pattern string The regular expression to search for.

Returns:

FunctionExpression

A new Expression representing the regular expression find function.

Example

// Extract the domain name from an email field
regexFind("email", "@[A-Za-z0-9.-]+");

regexFind(fieldName, pattern)

Creates an expression that returns the first substring of a string field that matches a specified regular expression.

This expression uses the RE2 regular expression syntax.

Signature:

export declare function regexFind(fieldName: string, pattern: Expression): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field containing the string to search.
pattern Expression The regular expression to search for.

Returns:

FunctionExpression

A new Expression representing the regular expression find function.

Example

// Extract a substring from 'email' based on a pattern stored in another field
regexFind("email", field("pattern"));

regexFindAll(fieldName, pattern)

Creates an expression that evaluates to a list of all substrings in a string field that match a specified regular expression.

This expression uses the RE2 regular expression syntax.

Signature:

export declare function regexFindAll(fieldName: string, pattern: string): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field containing the string to search.
pattern string The regular expression to search for.

Returns:

FunctionExpression

A new FunctionExpression that evaluates to an array of matched substrings.

Example

// Extract all hashtags from a post content field
regexFindAll("content", "#[A-Za-z0-9_]+");

regexFindAll(fieldName, pattern)

Creates an expression that evaluates to a list of all substrings in a string field that match a specified regular expression.

This expression uses the RE2 regular expression syntax.

Signature:

export declare function regexFindAll(fieldName: string, pattern: Expression): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field containing the string to search.
pattern Expression The regular expression to search for.

Returns:

FunctionExpression

A new FunctionExpression that evaluates to an array of matched substrings.

Example

// Extract all matches from 'content' based on a pattern stored in another field
regexFindAll("content", field("pattern"));

regexMatch(fieldName, pattern)

Creates an expression that checks if a string field matches a specified regular expression.

Signature:

export declare function regexMatch(fieldName: string, pattern: string): BooleanExpression;

Parameters

Parameter Type Description
fieldName string The name of the field containing the string.
pattern string The regular expression to use for the match.

Returns:

BooleanExpression

A new Expression representing the regular expression match.

Example

// Check if the 'email' field matches a valid email pattern
regexMatch("email", "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}");

regexMatch(fieldName, pattern)

Creates an expression that checks if a string field matches a specified regular expression.

Signature:

export declare function regexMatch(fieldName: string, pattern: Expression): BooleanExpression;

Parameters

Parameter Type Description
fieldName string The name of the field containing the string.
pattern Expression The regular expression to use for the match.

Returns:

BooleanExpression

A new Expression representing the regular expression match.

Example

// Check if the 'email' field matches a valid email pattern
regexMatch("email", field("pattern"));

round(fieldName)

Creates an expression that rounds a numeric value to the nearest whole number.

Signature:

export declare function round(fieldName: string): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field to round.

Returns:

FunctionExpression

A new Expression representing the rounded value.

Example

// Round the value of the 'price' field.
round("price");

round(fieldName, decimalPlaces)

Creates an expression that rounds a numeric value to the specified number of decimal places.

Signature:

export declare function round(fieldName: string, decimalPlaces: number | Expression): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field to round.
decimalPlaces number | Expression A constant or expression specifying the rounding precision in decimal places.

Returns:

FunctionExpression

A new Expression representing the rounded value.

Example

// Round the value of the 'price' field to two decimal places.
round("price", 2);

rtrim(fieldName, valueToTrim)

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

Signature:

export declare function rtrim(fieldName: string, valueToTrim?: string | Expression | Bytes): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field containing the string or byte array.
valueToTrim string | Expression | Bytes Optional. A string or byte array containing the characters/bytes to trim. If not specified, whitespace will be trimmed.

Returns:

FunctionExpression

A new Expression representing the trimmed string or byte array.

Example

// Trim whitespace from the end of the 'userInput' field
rtrim(field("userInput"));

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

split(fieldName, delimiter)

Creates an expression that splits the value of a field on the provided delimiter.

Signature:

export declare function split(fieldName: string, delimiter: string): FunctionExpression;

Parameters

Parameter Type Description
fieldName string Split the value in this field.
delimiter string Split on this delimiter.

Returns:

FunctionExpression

A new Expression representing the split function.

Example

// Split the 'scoresCsv' field on delimiter ','
split('scoresCsv', ',')

split(fieldName, delimiter)

Creates an expression that splits the value of a field on the provided delimiter.

Signature:

export declare function split(fieldName: string, delimiter: Expression): FunctionExpression;

Parameters

Parameter Type Description
fieldName string Split the value in this field.
delimiter Expression Split on this delimiter returned by evaluating this expression.

Returns:

FunctionExpression

A new Expression representing the split function.

Example

// Split the 'scores' field on delimiter ',' or ':' depending on the stored format
split('scores', conditional(field('format').equal('csv'), constant(','), constant(':')))

sqrt(fieldName)

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

Signature:

export declare function sqrt(fieldName: string): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field to compute the square root of.

Returns:

FunctionExpression

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

Example

// Compute the square root of the 'value' field.
sqrt("value");

startsWith(fieldName, prefix)

Creates an expression that checks if a field's value starts with a given prefix.

Signature:

export declare function startsWith(fieldName: string, prefix: string): BooleanExpression;

Parameters

Parameter Type Description
fieldName string The field name to check.
prefix string The prefix to check for.

Returns:

BooleanExpression

A new Expression representing the 'starts with' comparison.

Example

// Check if the 'name' field starts with "Mr."
startsWith("name", "Mr.");

startsWith(fieldName, prefix)

Creates an expression that checks if a field's value starts with a given prefix.

Signature:

export declare function startsWith(fieldName: string, prefix: Expression): BooleanExpression;

Parameters

Parameter Type Description
fieldName string The field name to check.
prefix Expression The expression representing the prefix.

Returns:

BooleanExpression

A new Expression representing the 'starts with' comparison.

Example

// Check if the 'fullName' field starts with the value of the 'firstName' field
startsWith("fullName", field("firstName"));

stringConcat(fieldName, secondString, otherStrings)

Creates an expression that concatenates string functions, fields or constants together.

Signature:

export declare function stringConcat(fieldName: string, secondString: Expression | string, ...otherStrings: Array<Expression | string>): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The field name containing the initial string value.
secondString Expression | string An expression or string literal to concatenate.
otherStrings Array<Expression | string> Optional additional expressions or literals (typically strings) to concatenate.

Returns:

FunctionExpression

A new Expression representing the concatenated string.

Example

// Combine the 'firstName', " ", and 'lastName' fields into a single string
stringConcat("firstName", " ", field("lastName"));

stringContains(fieldName, substring)

Creates an expression that checks if a string field contains a specified substring.

Signature:

export declare function stringContains(fieldName: string, substring: string): BooleanExpression;

Parameters

Parameter Type Description
fieldName string The name of the field containing the string.
substring string The substring to search for.

Returns:

BooleanExpression

A new Expression representing the 'contains' comparison.

Example

// Check if the 'description' field contains "example".
stringContains("description", "example");

stringContains(fieldName, substring)

Creates an expression that checks if a string field contains a substring specified by an expression.

Signature:

export declare function stringContains(fieldName: string, substring: Expression): BooleanExpression;

Parameters

Parameter Type Description
fieldName string The name of the field containing the string.
substring Expression The expression representing the substring to search for.

Returns:

BooleanExpression

A new Expression representing the 'contains' comparison.

Example

// Check if the 'description' field contains the value of the 'keyword' field.
stringContains("description", field("keyword"));

stringIndexOf(fieldName, search)

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

Signature:

export declare function stringIndexOf(fieldName: string, search: string | Expression | Bytes): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field containing the string or byte array.
search string | Expression | Bytes The substring or byte sequence to search for.

Returns:

FunctionExpression

A new Expression representing the index of the first occurrence.

Example

// Find the index of "foo" in the 'text' field
stringIndexOf("text", "foo");

stringRepeat(fieldName, repetitions)

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

Signature:

export declare function stringRepeat(fieldName: string, repetitions: number | Expression): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field containing the string or byte array.
repetitions number | Expression The number of times to repeat the string or byte array.

Returns:

FunctionExpression

A new Expression representing the repeated string or byte array.

Example

// Repeat the 'label' field 3 times
stringRepeat("label", 3);

stringReplaceAll(fieldName, find, replacement)

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

Signature:

export declare function stringReplaceAll(fieldName: string, find: string | Expression | Bytes, replacement: string | Expression | Bytes): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field containing the string or byte array.
find string | Expression | Bytes The substring or byte sequence to search for.
replacement string | Expression | Bytes The replacement string or byte sequence.

Returns:

FunctionExpression

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

Example

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

stringReplaceOne(fieldName, find, replacement)

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

Signature:

export declare function stringReplaceOne(fieldName: string, find: string | Expression | Bytes, replacement: string | Expression | Bytes): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field containing the string or byte array.
find string | Expression | Bytes The substring or byte sequence to search for.
replacement string | Expression | Bytes The replacement string or byte sequence.

Returns:

FunctionExpression

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

Example

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

subtract(fieldName, expression)

Creates an expression that subtracts an expression from a field's value.

Signature:

export declare function subtract(fieldName: string, expression: Expression): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The field name to subtract from.
expression Expression The expression to subtract.

Returns:

FunctionExpression

A new Expression representing the subtraction operation.

Example

// Subtract the 'discount' field from the 'price' field
subtract("price", field("discount"));

subtract(fieldName, value)

Creates an expression that subtracts a constant value from a field's value.

Signature:

export declare function subtract(fieldName: string, value: unknown): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The field name to subtract from.
value unknown The constant value to subtract.

Returns:

FunctionExpression

A new Expression representing the subtraction operation.

Example

// Subtract 20 from the value of the 'total' field
subtract("total", 20);

sum(fieldName)

Creates an aggregation that calculates the sum of a field's values across multiple stage inputs.

Signature:

export declare function sum(fieldName: string): AggregateFunction;

Parameters

Parameter Type Description
fieldName string The name of the field containing numeric values to sum up.

Returns:

AggregateFunction

A new AggregateFunction representing the 'sum' aggregation.

Example

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

timestampAdd(fieldName, unit, amount)

Creates an expression that adds a specified amount of time to a timestamp represented by a field.

Signature:

export declare function timestampAdd(fieldName: string, unit: TimeUnit, amount: number): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field representing the timestamp.
unit TimeUnit The unit of time to add (e.g., "day", "hour").
amount number The amount of time to add.

Returns:

FunctionExpression

A new Expression representing the resulting timestamp.

Example

// Add 1 day to the 'timestamp' field.
timestampAdd("timestamp", "day", 1);

timestampExtract(fieldName, part, timezone)

Creates an expression that extracts a specified part from a timestamp.

Signature:

export declare function timestampExtract(fieldName: string, part: TimePart, timezone?: string | Expression): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field representing the timestamp.
part TimePart The part to extract from the timestamp (e.g., "year", "month", "day").
timezone string | Expression The timezone to use for extraction. Valid values are from the TZ database (e.g., "America/Los_Angeles") or in the format "Etc/GMT-1."

Returns:

FunctionExpression

A new Expression representing the extracted part as an integer.

Example

// Extract the year from the 'createdAt' timestamp.
timestampExtract('createdAt', 'year')

timestampExtract(fieldName, part, timezone)

Creates an expression that extracts a specified part from a timestamp.

Signature:

export declare function timestampExtract(fieldName: string, part: Expression, timezone?: string | Expression): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field representing the timestamp.
part Expression The expression evaluating to the part to extract.
timezone string | Expression The timezone to use for extraction. Valid values are from the TZ database (e.g., "America/Los_Angeles") or in the format "Etc/GMT-1."

Returns:

FunctionExpression

A new Expression representing the extracted part as an integer.

Example

// Extract the part specified by the field 'part' from 'createdAt'.
timestampExtract('createdAt', field('part'))

timestampSubtract(fieldName, unit, amount)

Creates an expression that subtracts a specified amount of time from a timestamp represented by a field.

Signature:

export declare function timestampSubtract(fieldName: string, unit: TimeUnit, amount: number): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field representing the timestamp.
unit TimeUnit The unit of time to subtract (e.g., "day", "hour").
amount number The amount of time to subtract.

Returns:

FunctionExpression

A new Expression representing the resulting timestamp.

Example

// Subtract 1 day from the 'timestamp' field.
timestampSubtract("timestamp", "day", 1);

timestampToUnixMicros(fieldName)

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

Signature:

export declare function timestampToUnixMicros(fieldName: string): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field representing the timestamp.

Returns:

FunctionExpression

A new Expression representing the number of microseconds since epoch.

Example

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

timestampToUnixMillis(fieldName)

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

Signature:

export declare function timestampToUnixMillis(fieldName: string): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field representing the timestamp.

Returns:

FunctionExpression

A new Expression representing the number of milliseconds since epoch.

Example

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

timestampToUnixSeconds(fieldName)

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

Signature:

export declare function timestampToUnixSeconds(fieldName: string): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field representing the timestamp.

Returns:

FunctionExpression

A new Expression representing the number of seconds since epoch.

Example

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

timestampTruncate(fieldName, granularity, timezone)

Creates an expression that truncates a timestamp to a specified granularity.

Signature:

export declare function timestampTruncate(fieldName: string, granularity: TimeGranularity, timezone?: string | Expression): FunctionExpression;

Parameters

Parameter Type Description
fieldName string Truncate the timestamp value contained in this field.
granularity TimeGranularity The granularity to truncate to.
timezone string | Expression The timezone to use for truncation. Valid values are from the TZ database (e.g., "America/Los_Angeles") or in the format "Etc/GMT-1".

Returns:

FunctionExpression

A new Expression representing the truncated timestamp.

Example

// Truncate the 'createdAt' timestamp to the beginning of the day.
timestampTruncate('createdAt', 'day')

timestampTruncate(fieldName, granularity, timezone)

Creates an expression that truncates a timestamp to a specified granularity.

Signature:

export declare function timestampTruncate(fieldName: string, granularity: Expression, timezone?: string | Expression): FunctionExpression;

Parameters

Parameter Type Description
fieldName string Truncate the timestamp value contained in this field.
granularity Expression The granularity to truncate to.
timezone string | Expression The timezone to use for truncation. Valid values are from the TZ database (e.g., "America/Los_Angeles") or in the format "Etc/GMT-1".

Returns:

FunctionExpression

A new Expression representing the truncated timestamp.

Example

// Truncate the 'createdAt' timestamp to the granularity specified in the field 'granularity'.
timestampTruncate('createdAt', field('granularity'))

toLower(fieldName)

Creates an expression that converts a string field to lowercase.

Signature:

export declare function toLower(fieldName: string): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field containing the string.

Returns:

FunctionExpression

A new Expression representing the lowercase string.

Example

// Convert the 'name' field to lowercase
toLower("name");

toUpper(fieldName)

Creates an expression that converts a string field to uppercase.

Signature:

export declare function toUpper(fieldName: string): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field containing the string.

Returns:

FunctionExpression

A new Expression representing the uppercase string.

Example

// Convert the 'title' field to uppercase
toUpper("title");

trim(fieldName, valueToTrim)

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

Signature:

export declare function trim(fieldName: string, valueToTrim?: string | Expression): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field containing the string or byte array.
valueToTrim string | Expression 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:

FunctionExpression

A new Expression representing the trimmed string.

Example

// Trim whitespace from the 'userInput' field
trim("userInput");

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

trunc(fieldName)

Creates an expression that truncates the numeric value of a field to an integer.

Signature:

export declare function trunc(fieldName: string): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field containing the number to truncate.

Returns:

FunctionExpression

A new Expression representing the truncated value.

Example

// Truncate the value of the 'rating' field
trunc("rating");

trunc(fieldName, decimalPlaces)

Creates an expression that truncates a numeric expression to the specified number of decimal places.

Signature:

export declare function trunc(fieldName: string, decimalPlaces: number | Expression): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field to truncate.
decimalPlaces number | Expression A constant or expression specifying the truncation precision in decimal places.

Returns:

FunctionExpression

A new Expression representing the truncated value.

Example

// Truncate the value of the 'rating' field to two decimal places.
trunc("rating", 2);

type(fieldName)

Creates an expression that returns the data type of the data in the specified field.

String inputs passed iteratively to this global function act as field() path lookups. If you wish to pass a string literal value, it must be wrapped: type(constant("my_string")).

Signature:

export declare function type(fieldName: string): FunctionExpression;

Parameters

Parameter Type Description
fieldName string

Returns:

FunctionExpression

A new Expression representing the data type.

Example

// Get the data type of the value in field 'title'
type('title')

unixMicrosToTimestamp(fieldName)

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

Signature:

export declare function unixMicrosToTimestamp(fieldName: string): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field representing the number of microseconds since epoch.

Returns:

FunctionExpression

A new Expression representing the timestamp.

Example

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

unixMillisToTimestamp(fieldName)

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

Signature:

export declare function unixMillisToTimestamp(fieldName: string): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field representing the number of milliseconds since epoch.

Returns:

FunctionExpression

A new Expression representing the timestamp.

Example

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

unixSecondsToTimestamp(fieldName)

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

Signature:

export declare function unixSecondsToTimestamp(fieldName: string): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field representing the number of seconds since epoch.

Returns:

FunctionExpression

A new Expression representing the timestamp.

Example

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

vectorLength(fieldName)

Creates an expression that calculates the length of a Firestore Vector represented by a field.

Signature:

export declare function vectorLength(fieldName: string): FunctionExpression;

Parameters

Parameter Type Description
fieldName string The name of the field representing the Firestore Vector.

Returns:

FunctionExpression

A new Expression representing the length of the array.

Example

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

function(first, ...)

add(first, second)

Creates an expression that adds two expressions together.

Signature:

export declare function add(first: Expression, second: Expression | unknown): FunctionExpression;

Parameters

Parameter Type Description
first Expression The first expression to add.
second Expression | unknown The second expression or literal to add.

Returns:

FunctionExpression

A new Expression representing the addition operation.

Example

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

and(first, second, more)

Creates an expression that performs a logical 'AND' operation on multiple filter conditions.

Signature:

export declare function and(first: BooleanExpression, second: BooleanExpression, ...more: BooleanExpression[]): BooleanExpression;

Parameters

Parameter Type Description
first BooleanExpression The first filter condition.
second BooleanExpression The second filter condition.
more BooleanExpression[] Additional filter conditions to 'AND' together.

Returns:

BooleanExpression

A new Expression representing the logical 'AND' operation.

Example

// Check if the 'age' field is greater than 18 AND the 'city' field is "London" AND
// the 'status' field is "active"
const condition = and(greaterThan("age", 18), equal("city", "London"), equal("status", "active"));

concat(first, second, others)

Creates an expression that concatenates strings, arrays, or blobs. Types cannot be mixed.

Signature:

export declare function concat(first: Expression, second: Expression | unknown, ...others: Array<Expression | unknown>): FunctionExpression;

Parameters

Parameter Type Description
first Expression The first expressions to concatenate.
second Expression | unknown The second literal or expression to concatenate.
others Array<Expression | unknown> Additional literals or expressions to concatenate.

Returns:

FunctionExpression

A new Expression representing the concatenation.

Example

// Concatenate the 'firstName' and 'lastName' fields with a space in between.
concat(field("firstName"), " ", field("lastName"))

logicalMaximum(first, second, others)

Creates an expression that returns the largest value between multiple input expressions or literal values. Based on Firestore's value type ordering.

Signature:

export declare function logicalMaximum(first: Expression, second: Expression | unknown, ...others: Array<Expression | unknown>): FunctionExpression;

Parameters

Parameter Type Description
first Expression The first operand expression.
second Expression | unknown The second expression or literal.
others Array<Expression | unknown> Optional additional expressions or literals.

Returns:

FunctionExpression

A new Expression representing the logical maximum operation.

Example

// Returns the largest value between the 'field1' field, the 'field2' field,
// and 1000
logicalMaximum(field("field1"), field("field2"), 1000);

logicalMinimum(first, second, others)

Creates an expression that returns the smallest value between multiple input expressions and literal values. Based on Firestore's value type ordering.

Signature:

export declare function logicalMinimum(first: Expression, second: Expression | unknown, ...others: Array<Expression | unknown>): FunctionExpression;

Parameters

Parameter Type Description
first Expression The first operand expression.
second Expression | unknown The second expression or literal.
others Array<Expression | unknown> Optional additional expressions or literals.

Returns:

FunctionExpression

A new Expression representing the logical minimum operation.

Example

// Returns the smallest value between the 'field1' field, the 'field2' field,
// and 1000.
logicalMinimum(field("field1"), field("field2"), 1000);

multiply(first, second)

Creates an expression that multiplies two expressions together.

Signature:

export declare function multiply(first: Expression, second: Expression | unknown): FunctionExpression;

Parameters

Parameter Type Description
first Expression The first expression to multiply.
second Expression | unknown The second expression or literal to multiply.

Returns:

FunctionExpression

A new Expression representing the multiplication operation.

Example

// Multiply the 'quantity' field by the 'price' field
multiply(field("quantity"), field("price"));

nor(first, second, more)

Creates an expression that performs a logical 'NOR' operation on multiple filter conditions.

Signature:

export declare function nor(first: BooleanExpression, second: BooleanExpression, ...more: BooleanExpression[]): BooleanExpression;

Parameters

Parameter Type Description
first BooleanExpression The first filter condition.
second BooleanExpression The second filter condition.
more BooleanExpression[] Additional filter conditions to 'NOR' together.

Returns:

BooleanExpression

A new BooleanExpression representing the logical 'NOR' operation.

Example

// Check if neither the 'age' field is greater than 18 nor the 'city' field is "London"
const condition = nor(
  greaterThan("age", 18),
  equal("city", "London")
);

or(first, second, more)

Creates an expression that performs a logical 'OR' operation on multiple filter conditions.

Signature:

export declare function or(first: BooleanExpression, second: BooleanExpression, ...more: BooleanExpression[]): BooleanExpression;

Parameters

Parameter Type Description
first BooleanExpression The first filter condition.
second BooleanExpression The second filter condition.
more BooleanExpression[] Additional filter conditions to 'OR' together.

Returns:

BooleanExpression

A new Expression representing the logical 'OR' operation.

Example

// Check if the 'age' field is greater than 18 OR the 'city' field is "London" OR
// the 'status' field is "active"
const condition = or(greaterThan("age", 18), equal("city", "London"), equal("status", "active"));

xor(first, second, additionalConditions)

Creates an expression that performs a logical 'XOR' (exclusive OR) operation on multiple BooleanExpressions.

Signature:

export declare function xor(first: BooleanExpression, second: BooleanExpression, ...additionalConditions: BooleanExpression[]): BooleanExpression;

Parameters

Parameter Type Description
first BooleanExpression The first condition.
second BooleanExpression The second condition.
additionalConditions BooleanExpression[] Additional conditions to 'XOR' together.

Returns:

BooleanExpression

A new Expression representing the logical 'XOR' operation.

Example

// Check if only one of the conditions is true: 'age' greater than 18, 'city' is "London",
// or 'status' is "active".
const condition = xor(
    greaterThan("age", 18),
    equal("city", "London"),
    equal("status", "active"));

function(firstArray, ...)

arrayConcat(firstArray, secondArray, otherArrays)

Creates an expression that concatenates an array expression with other arrays.

Signature:

export declare function arrayConcat(firstArray: Expression, secondArray: Expression | unknown[], ...otherArrays: Array<Expression | unknown[]>): FunctionExpression;

Parameters

Parameter Type Description
firstArray Expression The first array expression to concatenate to.
secondArray Expression | unknown[] The second array expression or array literal to concatenate to.
otherArrays Array<Expression | unknown[]> Optional additional array expressions or array literals to concatenate.

Returns:

FunctionExpression

A new Expression representing the concatenated array.

Example

// Combine the 'items' array with two new item arrays
arrayConcat(field("items"), [field("newItems"), field("otherItems")]);

function(firstArrayField, ...)

arrayConcat(firstArrayField, secondArray, otherArrays)

Creates an expression that concatenates a field's array value with other arrays.

Signature:

export declare function arrayConcat(firstArrayField: string, secondArray: Expression | unknown[], ...otherArrays: Array<Expression | unknown[]>): FunctionExpression;

Parameters

Parameter Type Description
firstArrayField string The first array to concatenate to.
secondArray Expression | unknown[] The second array expression or array literal to concatenate to.
otherArrays Array<Expression | unknown[]> Optional additional array expressions or array literals to concatenate.

Returns:

FunctionExpression

A new Expression representing the concatenated array.

Example

// Combine the 'items' array with two new item arrays
arrayConcat("items", [field("newItems"), field("otherItems")]);

function(firstMap, ...)

mapMerge(firstMap, secondMap, otherMaps)

Creates an expression that merges multiple map values.

Signature:

export declare function mapMerge(firstMap: Record<string, unknown> | Expression, secondMap: Record<string, unknown> | Expression, ...otherMaps: Array<Record<string, unknown> | Expression>): FunctionExpression;

Parameters

Parameter Type Description
firstMap Record<string, unknown> | Expression An expression or literal map value that will be merged.
secondMap Record<string, unknown> | Expression A required second map to merge. Represented as a literal or an expression that returns a map.
otherMaps Array<Record<string, unknown> | Expression> Optional additional maps to merge. Each map is represented as a literal or an expression that returns a map.

Returns:

FunctionExpression

Example

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

function(firstString, ...)

stringConcat(firstString, secondString, otherStrings)

Creates an expression that concatenates string expressions together.

Signature:

export declare function stringConcat(firstString: Expression, secondString: Expression | string, ...otherStrings: Array<Expression | string>): FunctionExpression;

Parameters

Parameter Type Description
firstString Expression The initial string expression to concatenate to.
secondString Expression | string An expression or string literal to concatenate.
otherStrings Array<Expression | string> Optional additional expressions or literals (typically strings) to concatenate.

Returns:

FunctionExpression

A new Expression representing the concatenated string.

Example

// Combine the 'firstName', " ", and 'lastName' fields into a single string
stringConcat(field("firstName"), " ", field("lastName"));

function(ifExpr, ...)

ifAbsent(ifExpr, elseExpr)

Creates an expression that returns the elseExpr argument if ifExpr is absent, else return the result of the ifExpr argument evaluation.

Signature:

export declare function ifAbsent(ifExpr: Expression, elseExpr: Expression): Expression;

Parameters

Parameter Type Description
ifExpr Expression The expression to check for absence.
elseExpr Expression The expression that will be evaluated and returned if [ifExpr] is absent.

Returns:

Expression

A new Expression representing the ifAbsent operation.

Example

// Returns the value of the optional field 'optional_field', or returns 'default_value'
// if the field is absent.
ifAbsent(field("optional_field"), constant("default_value"))

ifAbsent(ifExpr, elseValue)

Creates an expression that returns the elseValue argument if ifExpr is absent, else return the result of the ifExpr argument evaluation.

Signature:

export declare function ifAbsent(ifExpr: Expression, elseValue: unknown): Expression;

Parameters

Parameter Type Description
ifExpr Expression The expression to check for absence.
elseValue unknown The value that will be returned if ifExpr evaluates to an absent value.

Returns:

Expression

A new [Expression] representing the ifAbsent operation.

Example

// Returns the value of the optional field 'optional_field', or returns 'default_value'
// if the field is absent.
ifAbsent(field("optional_field"), "default_value")

ifNull(ifExpr, elseExpr)

Creates an expression that returns the elseExpr argument if ifExpr is null, else return the result of the ifExpr argument evaluation.

This function provides a fallback for both absent and explicit null values. In contrast, ifAbsent() only triggers for missing fields.

Signature:

export declare function ifNull(ifExpr: Expression, elseExpr: Expression): FunctionExpression;

Parameters

Parameter Type Description
ifExpr Expression The expression to check for null.
elseExpr Expression The expression that will be evaluated and returned if ifExpr is null.

Returns:

FunctionExpression

A new Expression representing the ifNull operation.

Example

// Returns the user's preferred name, or if that is null, returns their full name.
ifNull(field("preferredName"), field("fullName"))

ifNull(ifExpr, elseValue)

Creates an expression that returns the elseValue argument if ifExpr is null, else return the result of the ifExpr argument evaluation.

This function provides a fallback for both absent and explicit null values. In contrast, ifAbsent() only triggers for missing fields.

Signature:

export declare function ifNull(ifExpr: Expression, elseValue: unknown): FunctionExpression;

Parameters

Parameter Type Description
ifExpr Expression The expression to check for null.
elseValue unknown The value that will be returned if ifExpr evaluates to null.

Returns:

FunctionExpression

A new Expression representing the ifNull operation.

Example

// Returns the user's display name, or returns "Anonymous" if the field is null.
ifNull(field("displayName"), "Anonymous")

function(ifFieldName, ...)

ifAbsent(ifFieldName, elseExpr)

Creates an expression that returns the elseExpr argument if ifFieldName is absent, else return the value of the field.

Signature:

export declare function ifAbsent(ifFieldName: string, elseExpr: Expression): Expression;

Parameters

Parameter Type Description
ifFieldName string The field to check for absence.
elseExpr Expression The expression that will be evaluated and returned if ifFieldName is absent.

Returns:

Expression

A new Expression representing the ifAbsent operation.

Example

// Returns the value of the optional field 'optional_field', or returns the value of
// 'default_field' if 'optional_field' is absent.
ifAbsent("optional_field", field("default_field"))

ifAbsent(ifFieldName, elseValue)

Creates an expression that returns the elseValue argument if ifFieldName is absent, else return the value of the field.

Signature:

export declare function ifAbsent(ifFieldName: string | Expression, elseValue: Expression | unknown): Expression;

Parameters

Parameter Type Description
ifFieldName string | Expression The field to check for absence.
elseValue Expression | unknown The value that will be returned if [ifFieldName] is absent.

Returns:

Expression

A new Expression representing the ifAbsent operation.

Example

// Returns the value of the optional field 'optional_field', or returns 'default_value'
// if the field is absent.
ifAbsent("optional_field", "default_value")

ifNull(ifFieldName, elseExpr)

Creates an expression that returns the elseExpr argument if ifFieldName field is null, else return the value of the field.

This function provides a fallback for both absent and explicit null values. In contrast, ifAbsent() only triggers for missing fields.

Signature:

export declare function ifNull(ifFieldName: string, elseExpr: Expression): FunctionExpression;

Parameters

Parameter Type Description
ifFieldName string The field to check for null.
elseExpr Expression The expression that will be evaluated and returned if ifFieldName is null.

Returns:

FunctionExpression

A new Expression representing the ifNull operation.

Example

// Returns the user's preferred name, or if that is null, returns their full name.
ifNull("preferredName", field("fullName"))

ifNull(ifFieldName, elseValue)

Creates an expression that returns the elseValue argument if ifFieldName field is null, else return the value of the field.

This function provides a fallback for both absent and explicit null values. In contrast, ifAbsent() only triggers for missing fields.

Signature:

export declare function ifNull(ifFieldName: string, elseValue: unknown): FunctionExpression;

Parameters

Parameter Type Description
ifFieldName string The field to check for null.
elseValue unknown The value that will be returned if ifFieldName is null.

Returns:

FunctionExpression

A new Expression representing the ifNull operation.

Example

// Returns the user's display name, or returns "Anonymous" if the field is null.
ifNull("displayName", "Anonymous")

function(input, ...)

substring(input, position, length)

Creates an expression that returns a substring of a string or byte array.

Signature:

export declare function substring(input: Expression, position: number, length?: number): FunctionExpression;

Parameters

Parameter Type Description
input Expression An expression returning a string or byte array to compute the substring from.
position number Index of the first character of the substring.
length number Length of the substring.

Returns:

FunctionExpression

substring(input, position, length)

Creates an expression that returns a substring of a string or byte array.

Signature:

export declare function substring(input: Expression, position: Expression, length?: Expression): FunctionExpression;

Parameters

Parameter Type Description
input Expression An expression returning a string or byte array to compute the substring from.
position Expression An expression that returns the index of the first character of the substring.
length Expression An expression that returns the length of the substring.

Returns:

FunctionExpression

function(left, ...)

divide(left, right)

Creates an expression that divides two expressions.

Signature:

export declare function divide(left: Expression, right: Expression): FunctionExpression;

Parameters

Parameter Type Description
left Expression The expression to be divided.
right Expression The expression to divide by.

Returns:

FunctionExpression

A new Expression representing the division operation.

Example

// Divide the 'total' field by the 'count' field
divide(field("total"), field("count"));

equal(left, right)

Creates an expression that checks if two expressions are equal.

Signature:

export declare function equal(left: Expression, right: Expression): BooleanExpression;

Parameters

Parameter Type Description
left Expression The first expression to compare.
right Expression The second expression to compare.

Returns:

BooleanExpression

A new Expression representing the equality comparison.

Example

// Check if the 'age' field is equal to an expression
equal(field("age"), field("minAge").add(10));

greaterThan(left, right)

Creates an expression that checks if the first expression is greater than the second expression.

Signature:

export declare function greaterThan(left: Expression, right: Expression): BooleanExpression;

Parameters

Parameter Type Description
left Expression The first expression to compare.
right Expression The second expression to compare.

Returns:

BooleanExpression

A new Expression representing the greater than comparison.

Example

// Check if the 'age' field is greater than 18
greaterThan(field("age"), constant(9).add(9));

greaterThanOrEqual(left, right)

Creates an expression that checks if the first expression is greater than or equal to the second expression.

Signature:

export declare function greaterThanOrEqual(left: Expression, right: Expression): BooleanExpression;

Parameters

Parameter Type Description
left Expression The first expression to compare.
right Expression The second expression to compare.

Returns:

BooleanExpression

A new Expression representing the greater than or equal to comparison.

Example

// Check if the 'quantity' field is greater than or equal to the field "threshold"
greaterThanOrEqual(field("quantity"), field("threshold"));

lessThan(left, right)

Creates an expression that checks if the first expression is less than the second expression.

Signature:

export declare function lessThan(left: Expression, right: Expression): BooleanExpression;

Parameters

Parameter Type Description
left Expression The first expression to compare.
right Expression The second expression to compare.

Returns:

BooleanExpression

A new Expression representing the less than comparison.

Example

// Check if the 'age' field is less than 30
lessThan(field("age"), field("limit"));

lessThanOrEqual(left, right)

Creates an expression that checks if the first expression is less than or equal to the second expression.

Signature:

export declare function lessThanOrEqual(left: Expression, right: Expression): BooleanExpression;

Parameters

Parameter Type Description
left Expression The first expression to compare.
right Expression The second expression to compare.

Returns:

BooleanExpression

A new Expression representing the less than or equal to comparison.

Example

// Check if the 'quantity' field is less than or equal to 20
lessThan(field("quantity"), field("limit"));

mod(left, right)

Creates an expression that calculates the modulo (remainder) of dividing two expressions.

Signature:

export declare function mod(left: Expression, right: Expression): FunctionExpression;

Parameters

Parameter Type Description
left Expression The dividend expression.
right Expression The divisor expression.

Returns:

FunctionExpression

A new Expression representing the modulo operation.

Example

// Calculate the remainder of dividing 'field1' by 'field2'.
mod(field("field1"), field("field2"));

notEqual(left, right)

Creates an expression that checks if two expressions are not equal.

Signature:

export declare function notEqual(left: Expression, right: Expression): BooleanExpression;

Parameters

Parameter Type Description
left Expression The first expression to compare.
right Expression The second expression to compare.

Returns:

BooleanExpression

A new Expression representing the inequality comparison.

Example

// Check if the 'status' field is not equal to field 'finalState'
notEqual(field("status"), field("finalState"));

subtract(left, right)

Creates an expression that subtracts two expressions.

Signature:

export declare function subtract(left: Expression, right: Expression): FunctionExpression;

Parameters

Parameter Type Description
left Expression The expression to subtract from.
right Expression The expression to subtract.

Returns:

FunctionExpression

A new Expression representing the subtraction operation.

Example

// Subtract the 'discount' field from the 'price' field
subtract(field("price"), field("discount"));

function(mapExpr, ...)

mapRemove(mapExpr, key)

Creates an expression that removes a key from the map produced by evaluating an expression.

Signature:

export declare function mapRemove(mapExpr: Expression, key: string): FunctionExpression;

Parameters

Parameter Type Description
mapExpr Expression An expression return a map value.
key string The name of the key to remove from the input map.

Returns:

FunctionExpression

Example

// Removes the key 'baz' from the input map.
mapRemove(map({foo: 'bar', baz: true}), 'baz');
@example

mapRemove(mapExpr, keyExpr)

Creates an expression that removes a key from the map produced by evaluating an expression.

Signature:

export declare function mapRemove(mapExpr: Expression, keyExpr: Expression): FunctionExpression;

Parameters

Parameter Type Description
mapExpr Expression An expression return a map value.
keyExpr Expression An expression that produces the name of the key to remove from the input map.

Returns:

FunctionExpression

Example

// Removes the key 'baz' from the input map.
mapRemove(map({foo: 'bar', baz: true}), constant('baz'));
@example

function(mapExpression, ...)

mapEntries(mapExpression)

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" }, ...].

While the backend generally preserves insertion order, relying on the order of the output array is not guaranteed and should be avoided.

Signature:

export declare function mapEntries(mapExpression: Expression): FunctionExpression;

Parameters

Parameter Type Description
mapExpression Expression The expression representing the map to get the entries of.

Returns:

FunctionExpression

A new Expression representing the entries of the map.

Example

// Get the entries of the map expression
mapEntries(map({"city": "San Francisco"}));

mapGet(mapExpression, subField)

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

Signature:

export declare function mapGet(mapExpression: Expression, subField: string): FunctionExpression;

Parameters

Parameter Type Description
mapExpression Expression The expression representing the map.
subField string The key to access in the map.

Returns:

FunctionExpression

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

Example

// Get the 'city' value from the 'address' map field
mapGet(field("address"), "city");

mapKeys(mapExpression)

Creates an expression that returns the keys of a map.

While the backend generally preserves insertion order, relying on the order of the output array is not guaranteed and should be avoided.

Signature:

export declare function mapKeys(mapExpression: Expression): FunctionExpression;

Parameters

Parameter Type Description
mapExpression Expression The expression representing the map to get the keys of.

Returns:

FunctionExpression

A new Expression representing the keys of the map.

Example

// Get the keys of the map expression
mapKeys(map({"city": "San Francisco"}));

mapSet(mapExpression, key, value, moreKeyValues)

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

This only performs shallow updates to the map. Setting a value to null will retain the key with a null value. To remove a key entirely, use mapRemove.

Signature:

export declare function mapSet(mapExpression: Expression, key: string | Expression, value: unknown, ...moreKeyValues: unknown[]): FunctionExpression;

Parameters

Parameter Type Description
mapExpression Expression The expression representing the map.
key string | Expression The key to set. Must be a string or a constant string expression.
value unknown The value to set.
moreKeyValues unknown[] Additional key-value pairs to set.

Returns:

FunctionExpression

A new Expression representing the map with the entries set.

Example

// Set the 'city' to "San Francisco"
mapSet(map({"state": "California"}), "city", "San Francisco");

mapValues(mapExpression)

Creates an expression that returns the values of a map.

While the backend generally preserves insertion order, relying on the order of the output array is not guaranteed and should be avoided.

Signature:

export declare function mapValues(mapExpression: Expression): FunctionExpression;

Parameters

Parameter Type Description
mapExpression Expression The expression representing the map to get the values of.

Returns:

FunctionExpression

A new Expression representing the values of the map.

Example

// Get the values of the map expression
mapValues(map({"city": "San Francisco"}));

function(mapField, ...)

mapEntries(mapField)

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" }, ...].

While the backend generally preserves insertion order, relying on the order of the output array is not guaranteed and should be avoided.

Signature:

export declare function mapEntries(mapField: string): FunctionExpression;

Parameters

Parameter Type Description
mapField string The map field to get the entries of.

Returns:

FunctionExpression

A new Expression representing the entries of the map.

Example

// Get the entries of the 'address' map field
mapEntries("address");

mapKeys(mapField)

Creates an expression that returns the keys of a map.

While the backend generally preserves insertion order, relying on the order of the output array is not guaranteed and should be avoided.

Signature:

export declare function mapKeys(mapField: string): FunctionExpression;

Parameters

Parameter Type Description
mapField string The map field to get the keys of.

Returns:

FunctionExpression

A new Expression representing the keys of the map.

Example

// Get the keys of the 'address' map field
mapKeys("address");

mapMerge(mapField, secondMap, otherMaps)

Creates an expression that merges multiple map values.

Signature:

export declare function mapMerge(mapField: string, secondMap: Record<string, unknown> | Expression, ...otherMaps: Array<Record<string, unknown> | Expression>): FunctionExpression;

Parameters

Parameter Type Description
mapField string Name of a field containing a map value that will be merged.
secondMap Record<string, unknown> | Expression A required second map to merge. Represented as a literal or an expression that returns a map.
otherMaps Array<Record<string, unknown> | Expression> Optional additional maps to merge. Each map is represented as a literal or an expression that returns a map.

Returns:

FunctionExpression

Example

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

mapRemove(mapField, key)

Creates an expression that removes a key from the map at the specified field name.

Signature:

export declare function mapRemove(mapField: string, key: string): FunctionExpression;

Parameters

Parameter Type Description
mapField string The name of a field containing a map value.
key string The name of the key to remove from the input map.

Returns:

FunctionExpression

Example

// Removes the key 'city' field from the map in the address field of the input document.
mapRemove('address', 'city');

mapRemove(mapField, keyExpr)

Creates an expression that removes a key from the map at the specified field name.

Signature:

export declare function mapRemove(mapField: string, keyExpr: Expression): FunctionExpression;

Parameters

Parameter Type Description
mapField string The name of a field containing a map value.
keyExpr Expression An expression that produces the name of the key to remove from the input map.

Returns:

FunctionExpression

Example

// Removes the key 'city' field from the map in the address field of the input document.
mapRemove('address', constant('city'));

mapSet(mapField, key, value, moreKeyValues)

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

This only performs shallow updates to the map. Setting a value to null will retain the key with a null value. To remove a key entirely, use mapRemove.

Signature:

export declare function mapSet(mapField: string, key: string | Expression, value: unknown, ...moreKeyValues: unknown[]): FunctionExpression;

Parameters

Parameter Type Description
mapField string The map field to set entries in.
key string | Expression The key to set. Must be a string or a constant string expression.
value unknown The value to set.
moreKeyValues unknown[] Additional key-value pairs to set.

Returns:

FunctionExpression

A new Expression representing the map with the entries set.

Example

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

mapValues(mapField)

Creates an expression that returns the values of a map.

While the backend generally preserves insertion order, relying on the order of the output array is not guaranteed and should be avoided.

Signature:

export declare function mapValues(mapField: string): FunctionExpression;

Parameters

Parameter Type Description
mapField string The map field to get the values of.

Returns:

FunctionExpression

A new Expression representing the values of the map.

Example

// Get the values of the 'address' map field
mapValues("address");

function(name, ...)

field(name)

Creates a Field instance representing the field at the given path.

The path can be a simple field name (e.g., "name") or a dot-separated path to a nested field (e.g., "address.city").

Signature:

export declare function field(name: string): Field;

Parameters

Parameter Type Description
name string The path to the field.

Returns:

Field

A new Field instance representing the specified field.

Example

// Create a Field instance for the 'title' field
const titleField = field("title");

// Create a Field instance for a nested field 'author.firstName'
const authorFirstNameField = field("author.firstName");

variable(name)

Creates an expression that retrieves the value of a variable bound via define().

Signature:

export declare function variable(name: string): Expression;

Parameters

Parameter Type Description
name string The name of the variable to retrieve.

Returns:

Expression

An Expression representing the variable's value.

Example

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

function(options, ...)

subcollection(options)

Creates a new Pipeline targeted at a subcollection relative to the current document context. This creates a pipeline without a database instance, suitable for embedding as a subquery. If executed directly, this pipeline will fail.

Signature:

export declare function subcollection(options: SubcollectionStageOptions): Pipeline;

Parameters

Parameter Type Description
options SubcollectionStageOptions Options defining how this SubcollectionStage is evaluated.

Returns:

Pipeline

function(path, ...)

field(path)

Creates a Field instance representing the field at the given path.

Signature:

export declare function field(path: FieldPath): Field;

Parameters

Parameter Type Description
path FieldPath A FieldPath specifying the field.

Returns:

Field

A new Field instance representing the specified field.

subcollection(path)

Creates a new Pipeline targeted at a subcollection relative to the current document context. This creates a pipeline without a database instance, suitable for embedding as a subquery. If executed directly, this pipeline will fail.

Signature:

export declare function subcollection(path: string): Pipeline;

Parameters

Parameter Type Description
path string The relative path to the subcollection.

Returns:

Pipeline

function(pipeline, ...)

execute(pipeline)

Executes this pipeline and returns a Promise to represent the asynchronous operation.

The returned Promise can be used to track the progress of the pipeline execution and retrieve the results (or handle any errors) asynchronously.

The pipeline results are returned as a PipelineSnapshot that contains a list of PipelineResult objects. Each PipelineResult typically represents a single key/value map that has passed through all the stages of the pipeline, however this might differ depending on the stages involved in the pipeline. For example:

  • If there are no stages or only transformation stages, each [PipelineResult](./firestore_pipelines.pipelineresult.md#pipelineresult_class) represents a single document.
  • If there is an aggregation, only a single [PipelineResult](./firestore_pipelines.pipelineresult.md#pipelineresult_class) is returned, representing the aggregated results over the entire dataset .
  • If there is an aggregation stage with grouping, each [PipelineResult](./firestore_pipelines.pipelineresult.md#pipelineresult_class) represents a distinct group and its associated aggregated values.

Signature:

export declare function execute(pipeline: Pipeline): Promise<PipelineSnapshot>;

Parameters

Parameter Type Description
pipeline Pipeline The pipeline to execute.

Returns:

Promise<PipelineSnapshot>

A Promise representing the asynchronous pipeline execution.

Example

const snapshot: PipelineSnapshot = await execute(firestore.pipeline().collection("books")
    .where(gt(field("rating"), 4.5))
    .select("title", "author", "rating"));

const results: PipelineResults = snapshot.results;

function(rquery, ...)

documentMatches(rquery)

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

Perform a full-text search on all indexed search fields in the document.

This Expression can only be used within a Search stage.

Signature:

export declare function documentMatches(rquery: string | Expression): BooleanExpression;

Parameters

Parameter Type Description
rquery string | Expression Define the search query using the search domain-specific language (DSL).

Returns:

BooleanExpression

Example

db.pipeline().collection('restaurants').search({
  query: documentMatches('waffles OR pancakes')
})

function(stringExpression, ...)

charLength(stringExpression)

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

Signature:

export declare function charLength(stringExpression: Expression): FunctionExpression;

Parameters

Parameter Type Description
stringExpression Expression The expression representing the string to calculate the length of.

Returns:

FunctionExpression

A new Expression representing the length of the string.

Example

// Get the character length of the 'name' field in UTF-8.
charLength(field("name"));

endsWith(stringExpression, suffix)

Creates an expression that checks if a string expression ends with a given postfix.

Signature:

export declare function endsWith(stringExpression: Expression, suffix: string): BooleanExpression;

Parameters

Parameter Type Description
stringExpression Expression The expression to check.
suffix string The postfix to check for.

Returns:

BooleanExpression

A new Expression representing the 'ends with' comparison.

Example

// Check if the result of concatenating 'firstName' and 'lastName' fields ends with "Jr."
endsWith(field("fullName"), "Jr.");

endsWith(stringExpression, suffix)

Creates an expression that checks if a string expression ends with a given postfix.

Signature:

export declare function endsWith(stringExpression: Expression, suffix: Expression): BooleanExpression;

Parameters

Parameter Type Description
stringExpression Expression The expression to check.
suffix Expression The postfix to check for.

Returns:

BooleanExpression

A new Expression representing the 'ends with' comparison.

Example

// Check if the result of concatenating 'firstName' and 'lastName' fields ends with "Jr."
endsWith(field("fullName"), constant("Jr."));

like(stringExpression, pattern)

Creates an expression that performs a case-sensitive wildcard string comparison.

Signature:

export declare function like(stringExpression: Expression, pattern: string): BooleanExpression;

Parameters

Parameter Type Description
stringExpression Expression The expression representing the string to perform the comparison on.
pattern string The pattern to search for. You can use "%" as a wildcard character.

Returns:

BooleanExpression

A new Expression representing the 'like' comparison.

Example

// Check if the 'title' field contains the string "guide"
like(field("title"), "%guide%");

like(stringExpression, pattern)

Creates an expression that performs a case-sensitive wildcard string comparison.

Signature:

export declare function like(stringExpression: Expression, pattern: Expression): BooleanExpression;

Parameters

Parameter Type Description
stringExpression Expression The expression representing the string to perform the comparison on.
pattern Expression The pattern to search for. You can use "%" as a wildcard character.

Returns:

BooleanExpression

A new Expression representing the 'like' comparison.

Example

// Check if the 'title' field contains the string "guide"
like(field("title"), field("pattern"));

regexContains(stringExpression, pattern)

Creates an expression that checks if a string expression contains a specified regular expression as a substring.

Signature:

export declare function regexContains(stringExpression: Expression, pattern: string): BooleanExpression;

Parameters

Parameter Type Description
stringExpression Expression The expression representing the string to perform the comparison on.
pattern string The regular expression to use for the search.

Returns:

BooleanExpression

A new Expression representing the 'contains' comparison.

Example

// Check if the 'description' field contains "example" (case-insensitive)
regexContains(field("description"), "(?i)example");

regexContains(stringExpression, pattern)

Creates an expression that checks if a string expression contains a specified regular expression as a substring.

Signature:

export declare function regexContains(stringExpression: Expression, pattern: Expression): BooleanExpression;

Parameters

Parameter Type Description
stringExpression Expression The expression representing the string to perform the comparison on.
pattern Expression The regular expression to use for the search.

Returns:

BooleanExpression

A new Expression representing the 'contains' comparison.

Example

// Check if the 'description' field contains "example" (case-insensitive)
regexContains(field("description"), field("pattern"));

regexFind(stringExpression, pattern)

Creates an expression that returns the first substring of a string expression that matches a specified regular expression.

This expression uses the RE2 regular expression syntax.

Signature:

export declare function regexFind(stringExpression: Expression, pattern: string): FunctionExpression;

Parameters

Parameter Type Description
stringExpression Expression The expression representing the string to search.
pattern string The regular expression to search for.

Returns:

FunctionExpression

A new Expression representing the regular expression find function.

Example

// Extract the domain from a lower-cased email address
regexFind(field("email"), "@[A-Za-z0-9.-]+");

regexFind(stringExpression, pattern)

Creates an expression that returns the first substring of a string expression that matches a specified regular expression.

This expression uses the RE2 regular expression syntax.

Signature:

export declare function regexFind(stringExpression: Expression, pattern: Expression): FunctionExpression;

Parameters

Parameter Type Description
stringExpression Expression The expression representing the string to search.
pattern Expression The regular expression to search for.

Returns:

FunctionExpression

A new Expression representing the regular expression find function.

Example

// Extract a substring based on a dynamic pattern field
regexFind(field("email"), field("pattern"));

regexFindAll(stringExpression, pattern)

Creates an expression that evaluates to a list of all substrings in a string expression that match a specified regular expression.

This expression uses the RE2 regular expression syntax.

Signature:

export declare function regexFindAll(stringExpression: Expression, pattern: string): FunctionExpression;

Parameters

Parameter Type Description
stringExpression Expression The expression representing the string to search.
pattern string The regular expression to search for.

Returns:

FunctionExpression

A new FunctionExpression that evaluates to an array of matched substrings.

Example

// Extract all mentions from a lower-cased comment
regexFindAll(field("comment"), "@[A-Za-z0-9_]+");

regexFindAll(stringExpression, pattern)

Creates an expression that evaluates to a list of all substrings in a string expression that match a specified regular expression.

This expression uses the RE2 regular expression syntax.

Signature:

export declare function regexFindAll(stringExpression: Expression, pattern: Expression): FunctionExpression;

Parameters

Parameter Type Description
stringExpression Expression The expression representing the string to search.
pattern Expression The regular expression to search for.

Returns:

FunctionExpression

A new FunctionExpression that evaluates to an array of matched substrings.

Example

// Extract all matches based on a dynamic pattern expression
regexFindAll(field("comment"), field("pattern"));

regexMatch(stringExpression, pattern)

Creates an expression that checks if a string expression matches a specified regular expression.

Signature:

export declare function regexMatch(stringExpression: Expression, pattern: string): BooleanExpression;

Parameters

Parameter Type Description
stringExpression Expression The expression representing the string to match against.
pattern string The regular expression to use for the match.

Returns:

BooleanExpression

A new Expression representing the regular expression match.

Example

// Check if the 'email' field matches a valid email pattern
regexMatch(field("email"), "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}");

regexMatch(stringExpression, pattern)

Creates an expression that checks if a string expression matches a specified regular expression.

Signature:

export declare function regexMatch(stringExpression: Expression, pattern: Expression): BooleanExpression;

Parameters

Parameter Type Description
stringExpression Expression The expression representing the string to match against.
pattern Expression The regular expression to use for the match.

Returns:

BooleanExpression

A new Expression representing the regular expression match.

Example

// Check if the 'email' field matches a valid email pattern
regexMatch(field("email"), field("pattern"));

reverse(stringExpression)

Creates an expression that reverses a string.

Signature:

export declare function reverse(stringExpression: Expression): FunctionExpression;

Parameters

Parameter Type Description
stringExpression Expression An expression evaluating to a string value, which will be reversed.

Returns:

FunctionExpression

A new Expression representing the reversed string.

Example

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

startsWith(stringExpression, prefix)

Creates an expression that checks if a string expression starts with a given prefix.

Signature:

export declare function startsWith(stringExpression: Expression, prefix: string): BooleanExpression;

Parameters

Parameter Type Description
stringExpression Expression The expression to check.
prefix string The prefix to check for.

Returns:

BooleanExpression

A new Expression representing the 'starts with' comparison.

Example

// Check if the result of concatenating 'firstName' and 'lastName' fields starts with "Mr."
startsWith(field("fullName"), "Mr.");

startsWith(stringExpression, prefix)

Creates an expression that checks if a string expression starts with a given prefix.

Signature:

export declare function startsWith(stringExpression: Expression, prefix: Expression): BooleanExpression;

Parameters

Parameter Type Description
stringExpression Expression The expression to check.
prefix Expression The prefix to check for.

Returns:

BooleanExpression

A new Expression representing the 'starts with' comparison.

Example

// Check if the result of concatenating 'firstName' and 'lastName' fields starts with "Mr."
startsWith(field("fullName"), field("prefix"));

stringContains(stringExpression, substring)

Creates an expression that checks if a string expression contains a specified substring.

Signature:

export declare function stringContains(stringExpression: Expression, substring: string): BooleanExpression;

Parameters

Parameter Type Description
stringExpression Expression The expression representing the string to perform the comparison on.
substring string The substring to search for.

Returns:

BooleanExpression

A new Expression representing the 'contains' comparison.

Example

// Check if the 'description' field contains "example".
stringContains(field("description"), "example");

stringContains(stringExpression, substring)

Creates an expression that checks if a string expression contains a substring specified by another expression.

Signature:

export declare function stringContains(stringExpression: Expression, substring: Expression): BooleanExpression;

Parameters

Parameter Type Description
stringExpression Expression The expression representing the string to perform the comparison on.
substring Expression The expression representing the substring to search for.

Returns:

BooleanExpression

A new Expression representing the 'contains' comparison.

Example

// Check if the 'description' field contains the value of the 'keyword' field.
stringContains(field("description"), field("keyword"));

stringReverse(stringExpression)

Creates an expression that reverses a string.

Signature:

export declare function stringReverse(stringExpression: Expression): FunctionExpression;

Parameters

Parameter Type Description
stringExpression Expression An expression evaluating to a string value, which will be reversed.

Returns:

FunctionExpression

A new Expression representing the reversed string.

Example

// Reverse the value of the 'myString' field.
stringReverse(field("myString"));

toLower(stringExpression)

Creates an expression that converts a string expression to lowercase.

Signature:

export declare function toLower(stringExpression: Expression): FunctionExpression;

Parameters

Parameter Type Description
stringExpression Expression The expression representing the string to convert to lowercase.

Returns:

FunctionExpression

A new Expression representing the lowercase string.

Example

// Convert the 'name' field to lowercase
toLower(field("name"));

toUpper(stringExpression)

Creates an expression that converts a string expression to uppercase.

Signature:

export declare function toUpper(stringExpression: Expression): FunctionExpression;

Parameters

Parameter Type Description
stringExpression Expression The expression representing the string to convert to uppercase.

Returns:

FunctionExpression

A new Expression representing the uppercase string.

Example

// Convert the 'title' field to uppercase
toUpper(field("title"));

trim(stringExpression, valueToTrim)

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

Signature:

export declare function trim(stringExpression: Expression, valueToTrim?: string | Expression): FunctionExpression;

Parameters

Parameter Type Description
stringExpression Expression The expression representing the string or byte array to trim.
valueToTrim string | Expression 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:

FunctionExpression

A new Expression representing the trimmed string or byte array.

Example

// Trim whitespace from the 'userInput' field
trim(field("userInput"));

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

function(timestamp, ...)

timestampAdd(timestamp, unit, amount)

Creates an expression that adds a specified amount of time to a timestamp.

Signature:

export declare function timestampAdd(timestamp: Expression, unit: Expression, amount: Expression): FunctionExpression;

Parameters

Parameter Type Description
timestamp Expression The expression representing the timestamp.
unit Expression The expression evaluates to unit of time, must be one of 'microsecond', 'millisecond', 'second', 'minute', 'hour', 'day'.
amount Expression The expression evaluates to amount of the unit.

Returns:

FunctionExpression

A new Expression representing the resulting timestamp.

Example

// Add some duration determined by field 'unit' and 'amount' to the 'timestamp' field.
timestampAdd(field("timestamp"), field("unit"), field("amount"));

timestampAdd(timestamp, unit, amount)

Creates an expression that adds a specified amount of time to a timestamp.

Signature:

export declare function timestampAdd(timestamp: Expression, unit: TimeUnit, amount: number): FunctionExpression;

Parameters

Parameter Type Description
timestamp Expression The expression representing the timestamp.
unit TimeUnit The unit of time to add (e.g., "day", "hour").
amount number The amount of time to add.

Returns:

FunctionExpression

A new Expression representing the resulting timestamp.

Example

// Add 1 day to the 'timestamp' field.
timestampAdd(field("timestamp"), "day", 1);

timestampSubtract(timestamp, unit, amount)

Creates an expression that subtracts a specified amount of time from a timestamp.

Signature:

export declare function timestampSubtract(timestamp: Expression, unit: Expression, amount: Expression): FunctionExpression;

Parameters

Parameter Type Description
timestamp Expression The expression representing the timestamp.
unit Expression The expression evaluates to unit of time, must be one of 'microsecond', 'millisecond', 'second', 'minute', 'hour', 'day'.
amount Expression The expression evaluates to amount of the unit.

Returns:

FunctionExpression

A new Expression representing the resulting timestamp.

Example

// Subtract some duration determined by field 'unit' and 'amount' from the 'timestamp' field.
timestampSubtract(field("timestamp"), field("unit"), field("amount"));

timestampSubtract(timestamp, unit, amount)

Creates an expression that subtracts a specified amount of time from a timestamp.

Signature:

export declare function timestampSubtract(timestamp: Expression, unit: TimeUnit, amount: number): FunctionExpression;

Parameters

Parameter Type Description
timestamp Expression The expression representing the timestamp.
unit TimeUnit The unit of time to subtract (e.g., "day", "hour").
amount number The amount of time to subtract.

Returns:

FunctionExpression

A new Expression representing the resulting timestamp.

Example

// Subtract 1 day from the 'timestamp' field.
timestampSubtract(field("timestamp"), "day", 1);

function(timestampExpression, ...)

timestampExtract(timestampExpression, part, timezone)

Creates an expression that extracts a specified part from a timestamp.

Signature:

export declare function timestampExtract(timestampExpression: Expression, part: TimePart, timezone?: string | Expression): FunctionExpression;

Parameters

Parameter Type Description
timestampExpression Expression The expression evaluating to the timestamp.
part TimePart The part to extract from the timestamp (e.g., "year", "month", "day").
timezone string | Expression The timezone to use for extraction. Valid values are from the TZ database (e.g., "America/Los_Angeles") or in the format "Etc/GMT-1."

Returns:

FunctionExpression

A new Expression representing the extracted part as an integer.

Example

// Extract the year from the timestamp returned by the expression.
timestampExtract(field('createdAt'), 'year')

timestampExtract(timestampExpression, part, timezone)

Creates an expression that extracts a specified part from a timestamp.

Signature:

export declare function timestampExtract(timestampExpression: Expression, part: Expression, timezone?: string | Expression): FunctionExpression;

Parameters

Parameter Type Description
timestampExpression Expression The expression evaluating to the timestamp.
part Expression The expression evaluating to the part to extract.
timezone string | Expression The timezone to use for extraction. Valid values are from the TZ database (e.g., "America/Los_Angeles") or in the format "Etc/GMT-1."

Returns:

FunctionExpression

A new Expression representing the extracted part as an integer.

Example

// Extract the part specified by the field 'part' from the timestamp.
timestampExtract(field('createdAt'), field('part'))

timestampTruncate(timestampExpression, granularity, timezone)

Creates an expression that truncates a timestamp to a specified granularity.

Signature:

export declare function timestampTruncate(timestampExpression: Expression, granularity: TimeGranularity, timezone?: string | Expression): FunctionExpression;

Parameters

Parameter Type Description
timestampExpression Expression Truncate the timestamp value that is returned by this expression.
granularity TimeGranularity The granularity to truncate to.
timezone string | Expression The timezone to use for truncation. Valid values are from the TZ database (e.g., "America/Los_Angeles") or in the format "Etc/GMT-1".

Returns:

FunctionExpression

A new Expression representing the truncated timestamp.

Example

// Truncate the 'createdAt' timestamp to the beginning of the day.
timestampTruncate(field('createdAt'), 'day')

timestampTruncate(timestampExpression, granularity, timezone)

Creates an expression that truncates a timestamp to a specified granularity.

Signature:

export declare function timestampTruncate(timestampExpression: Expression, granularity: Expression, timezone?: string | Expression): FunctionExpression;

Parameters

Parameter Type Description
timestampExpression Expression Truncate the timestamp value that is returned by this expression.
granularity Expression The granularity to truncate to.
timezone string | Expression The timezone to use for truncation. Valid values are from the TZ database (e.g., "America/Los_Angeles") or in the format "Etc/GMT-1".

Returns:

FunctionExpression

A new Expression representing the truncated timestamp.

Example

// Truncate the 'createdAt' timestamp to the granularity specified in the field 'granularity'.
timestampTruncate(field('createdAt'), field('granularity'))

function(tryExpr, ...)

ifError(tryExpr, catchExpr)

Creates an expression that returns the catch argument if there is an error, else return the result of the try argument evaluation.

This overload is useful when a BooleanExpression is required.

Signature:

export declare function ifError(tryExpr: BooleanExpression, catchExpr: BooleanExpression): BooleanExpression;

Parameters

Parameter Type Description
tryExpr BooleanExpression The try expression.
catchExpr BooleanExpression The catch expression that will be evaluated and returned if the tryExpr produces an error.

Returns:

BooleanExpression

A new Expression representing the 'ifError' operation.

Example

// Create an expression that protects against a divide by zero error
// but always returns a boolean expression.
ifError(constant(50).divide(field('length')).greaterThan(1), constant(false));

ifError(tryExpr, catchExpr)

Creates an expression that returns the catch argument if there is an error, else return the result of the try argument evaluation.

Signature:

export declare function ifError(tryExpr: Expression, catchExpr: Expression): FunctionExpression;

Parameters

Parameter Type Description
tryExpr Expression The try expression.
catchExpr Expression The catch expression that will be evaluated and returned if the tryExpr produces an error.

Returns:

FunctionExpression

A new Expression representing the 'ifError' operation.

Example

// Returns the first item in the title field arrays, or returns
// the entire title field if the array is empty or the field is another type.
ifError(field("title").arrayGet(0), field("title"));

ifError(tryExpr, catchValue)

Creates an expression that returns the catch argument if there is an error, else return the result of the try argument evaluation.

Signature:

export declare function ifError(tryExpr: Expression, catchValue: unknown): FunctionExpression;

Parameters

Parameter Type Description
tryExpr Expression The try expression.
catchValue unknown The value that will be returned if the tryExpr produces an error.

Returns:

FunctionExpression

A new Expression representing the 'ifError' operation.

Example

// Returns the first item in the title field arrays, or returns
// "Default Title"
ifError(field("title").arrayGet(0), "Default Title");

function(value, ...)

constant(value)

Creates a Constant instance for a number value.

Signature:

export declare function constant(value: number): Expression;

Parameters

Parameter Type Description
value number The number value.

Returns:

Expression

A new Constant instance.

constant(value)

Creates a Constant instance for a VectorValue value.

Signature:

export declare function constant(value: VectorValue): Expression;

Parameters

Parameter Type Description
value VectorValue The VectorValue value.

Returns:

Expression

A new Constant instance.

constant(value)

Creates a Constant instance for a string value.

Signature:

export declare function constant(value: string): Expression;

Parameters

Parameter Type Description
value string The string value.

Returns:

Expression

A new Constant instance.

constant(value)

Creates a BooleanExpression instance for a boolean value.

Signature:

export declare function constant(value: boolean): BooleanExpression;

Parameters

Parameter Type Description
value boolean The boolean value.

Returns:

BooleanExpression

A new Constant instance.

constant(value)

Creates a Constant instance for a null value.

Signature:

export declare function constant(value: null): Expression;

Parameters

Parameter Type Description
value null The null value.

Returns:

Expression

A new Constant instance.

constant(value)

Creates a Constant instance for a GeoPoint value.

Signature:

export declare function constant(value: GeoPoint): Expression;

Parameters

Parameter Type Description
value GeoPoint The GeoPoint value.

Returns:

Expression

A new Constant instance.

constant(value)

Creates a Constant instance for a Timestamp value.

Signature:

export declare function constant(value: Timestamp): Expression;

Parameters

Parameter Type Description
value Timestamp The Timestamp value.

Returns:

Expression

A new Constant instance.

constant(value)

Creates a Constant instance for a Date value.

Signature:

export declare function constant(value: Date): Expression;

Parameters

Parameter Type Description
value Date The Date value.

Returns:

Expression

A new Constant instance.

constant(value)

Creates a Constant instance for a Bytes value.

Signature:

export declare function constant(value: Bytes): Expression;

Parameters

Parameter Type Description
value Bytes The Bytes value.

Returns:

Expression

A new Constant instance.

constant(value)

Creates a Constant instance for a DocumentReference value.

Signature:

export declare function constant(value: DocumentReference): Expression;

Parameters

Parameter Type Description
value DocumentReference The DocumentReference value.

Returns:

Expression

A new Constant instance.

exists(value)

Creates an expression that checks if a field exists.

Signature:

export declare function exists(value: Expression): BooleanExpression;

Parameters

Parameter Type Description
value Expression An expression evaluates to the name of the field to check.

Returns:

BooleanExpression

A new Expression representing the 'exists' check.

Example

// Check if the document has a field named "phoneNumber"
exists(field("phoneNumber"));

isAbsent(value)

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

Signature:

export declare function isAbsent(value: Expression): BooleanExpression;

Parameters

Parameter Type Description
value Expression The expression to check.

Returns:

BooleanExpression

A new Expression representing the 'isAbsent' check.

Example

// Check if the field `value` is absent.
isAbsent(field("value"));

isError(value)

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

Signature:

export declare function isError(value: Expression): BooleanExpression;

Parameters

Parameter Type Description
value Expression The expression to check.

Returns:

BooleanExpression

A new Expression representing the 'isError' check.

Example

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

function(vectorExpression, ...)

cosineDistance(vectorExpression, vector)

Calculates the Cosine distance between a vector expression and a vector literal.

Signature:

export declare function cosineDistance(vectorExpression: Expression, vector: number[] | VectorValue): FunctionExpression;

Parameters

Parameter Type Description
vectorExpression Expression The first vector (represented as an Expression) to compare against.
vector number[] | VectorValue The other vector (as an array of doubles or VectorValue) to compare against.

Returns:

FunctionExpression

A new Expression representing the cosine distance between the two vectors.

Example

// Calculate the cosine distance between the 'location' field and a target location
cosineDistance(field("location"), [37.7749, -122.4194]);

cosineDistance(vectorExpression, otherVectorExpression)

Calculates the Cosine distance between two vector expressions.

Signature:

export declare function cosineDistance(vectorExpression: Expression, otherVectorExpression: Expression): FunctionExpression;

Parameters

Parameter Type Description
vectorExpression Expression The first vector (represented as an Expression) to compare against.
otherVectorExpression Expression The other vector (represented as an Expression) to compare against.

Returns:

FunctionExpression

A new Expression representing the cosine distance between the two vectors.

Example

// Calculate the cosine distance between the 'userVector' field and the 'itemVector' field
cosineDistance(field("userVector"), field("itemVector"));

dotProduct(vectorExpression, vector)

Calculates the dot product between a vector expression and a double array.

Signature:

export declare function dotProduct(vectorExpression: Expression, vector: number[] | VectorValue): FunctionExpression;

Parameters

Parameter Type Description
vectorExpression Expression The first vector (represented as an Expression) to calculate with.
vector number[] | VectorValue The other vector (as an array of doubles or VectorValue) to calculate with.

Returns:

FunctionExpression

A new Expression representing the dot product between the two vectors.

Example

// Calculate the dot product between a feature vector and a target vector
dotProduct(field("features"), [0.5, 0.8, 0.2]);

dotProduct(vectorExpression, otherVectorExpression)

Calculates the dot product between two vector expressions.

Signature:

export declare function dotProduct(vectorExpression: Expression, otherVectorExpression: Expression): FunctionExpression;

Parameters

Parameter Type Description
vectorExpression Expression The first vector (represented as an Expression) to calculate with.
otherVectorExpression Expression The other vector (represented as an Expression) to calculate with.

Returns:

FunctionExpression

A new Expression representing the dot product between the two vectors.

Example

// Calculate the dot product between two document vectors: 'docVector1' and 'docVector2'
dotProduct(field("docVector1"), field("docVector2"));

euclideanDistance(vectorExpression, vector)

Calculates the Euclidean distance between a vector expression and a double array.

Signature:

export declare function euclideanDistance(vectorExpression: Expression, vector: number[] | VectorValue): FunctionExpression;

Parameters

Parameter Type Description
vectorExpression Expression The first vector (represented as an Expression) to compare against.
vector number[] | VectorValue The other vector (as an array of doubles or VectorValue) to compare against.

Returns:

FunctionExpression

A new Expression representing the Euclidean distance between the two vectors.

Example

// Calculate the Euclidean distance between the 'location' field and a target location

euclideanDistance(field("location"), [37.7749, -122.4194]);

euclideanDistance(vectorExpression, otherVectorExpression)

Calculates the Euclidean distance between two vector expressions.

Signature:

export declare function euclideanDistance(vectorExpression: Expression, otherVectorExpression: Expression): FunctionExpression;

Parameters

Parameter Type Description
vectorExpression Expression The first vector (represented as an Expression) to compare against.
otherVectorExpression Expression The other vector (represented as an Expression) to compare against.

Returns:

FunctionExpression

A new Expression representing the Euclidean distance between the two vectors.

Example

// Calculate the Euclidean distance between two vector fields: 'pointA' and 'pointB'
euclideanDistance(field("pointA"), field("pointB"));

vectorLength(vectorExpression)

Creates an expression that calculates the length of a Firestore Vector.

Signature:

export declare function vectorLength(vectorExpression: Expression): FunctionExpression;

Parameters

Parameter Type Description
vectorExpression Expression The expression representing the Firestore Vector.

Returns:

FunctionExpression

A new Expression representing the length of the array.

Example

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

AddFieldsStageOptions

Options defining how an AddFieldsStage is evaluated. See Pipeline.addFields().

Signature:

export declare type AddFieldsStageOptions = StageOptions & {
    fields: Selectable[];
};

AggregateStageOptions

Options defining how an AggregateStage is evaluated. See Pipeline.aggregate().

Signature:

export declare type AggregateStageOptions = StageOptions & {
    accumulators: AliasedAggregate[];
    groups?: Array<string | Selectable>;
};

CollectionGroupStageOptions

Defines the configuration options for a CollectionGroupStage within a pipeline. This type extends StageOptions and provides specific settings for how a collection group is identified and processed during pipeline execution.

See PipelineSource.collectionGroup() to create a collection group stage.

Signature:

export declare type CollectionGroupStageOptions = StageOptions & {
    collectionId: string;
    forceIndex?: string;
};

CollectionStageOptions

Options defining how a CollectionStage is evaluated. See PipelineSource.collection().

Signature:

export declare type CollectionStageOptions = StageOptions & {
    collection: string | Query;
    forceIndex?: string;
};

DatabaseStageOptions

Options defining how a DatabaseStage is evaluated. See PipelineSource.database().

Signature:

export declare type DatabaseStageOptions = StageOptions & {};

DefineStageOptions

Options defining how a DefineStage is evaluated. See Pipeline.define().

Signature:

export declare type DefineStageOptions = StageOptions & {
    variables: AliasedExpression[];
};

DistinctStageOptions

Options defining how a DistinctStage is evaluated. See Pipeline.distinct().

Signature:

export declare type DistinctStageOptions = StageOptions & {
    groups: Array<string | Selectable>;
};

DocumentsStageOptions

Options defining how a DocumentsStage is evaluated. See PipelineSource.documents().

Signature:

export declare type DocumentsStageOptions = StageOptions & {
    docs: Array<string | DocumentReference>;
};

ExpressionType

An enumeration of the different types of expressions.

Signature:

export declare type ExpressionType = 'Field' | 'Constant' | 'Function' | 'AggregateFunction' | 'ListOfExpressions' | 'AliasedExpression' | 'Variable' | 'PipelineValue';

FindNearestStageOptions

Options defining how a FindNearestStage is evaluated. See Pipeline.findNearest().

Signature:

export declare type FindNearestStageOptions = StageOptions & {
    field: Field | string;
    vectorValue: VectorValue | number[];
    distanceMeasure: 'euclidean' | 'cosine' | 'dot_product';
    limit?: number;
    distanceField?: string;
};

LimitStageOptions

Options defining how a LimitStage is evaluated. See Pipeline.limit().

Signature:

export declare type LimitStageOptions = StageOptions & {
    limit: number;
};

OffsetStageOptions

Options defining how an OffsetStage is evaluated. See Pipeline.offset().

Signature:

export declare type OffsetStageOptions = StageOptions & {
    offset: number;
};

OneOf

Utility type to create an type that only allows one property of the Type param T to be set.

Signature:

export declare type OneOf<T> = {
    [K in keyof T]: Pick<T, K> & {
        [P in Exclude<keyof T, K>]?: undefined;
    };
}[keyof T];

Example

type XorY = OneOf<{ x: unknown, y: unknown }>
let a = { x: "foo" }           // OK
let b = { y: "foo" }           // OK
let c = { a: "foo", y: "foo" } // Not OK

PartialWithFieldValue

Similar to TypeScript's Partial<T>, but allows nested fields to be omitted and FieldValues to be passed in as property values.

Signature:

export declare type PartialWithFieldValue<T> = Partial<T> | (T extends Primitive ? T : T extends {} ? {
    [K in keyof T]?: PartialWithFieldValue<T[K]> | FieldValue;
} : never);

Primitive

Primitive types.

Signature:

export declare type Primitive = string | number | boolean | undefined | null;

RemoveFieldsStageOptions

Options defining how a RemoveFieldsStage is evaluated. See Pipeline.removeFields().

Signature:

export declare type RemoveFieldsStageOptions = StageOptions & {
    fields: Array<Field | string>;
};

ReplaceWithStageOptions

Options defining how a ReplaceWithStage is evaluated. See Pipeline.replaceWith().

Signature:

export declare type ReplaceWithStageOptions = StageOptions & {
    map: Expression | string;
};

SampleStageOptions

Defines the options for evaluating a sample stage within a pipeline. This type combines common StageOptions with a specific configuration where only one of the defined sampling methods can be applied.

See Pipeline.sample() to create a sample stage..

Signature:

export declare type SampleStageOptions = StageOptions & OneOf<{
    percentage: number;
    documents: number;
}>;

SearchStageOptions

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

Options defining how a SearchStage is evaluated. See .

Signature:

export declare type SearchStageOptions = StageOptions & {
    query: BooleanExpression | string;
    sort?: Ordering | Ordering[];
    addFields?: Selectable[];
};

SelectStageOptions

Options defining how a SelectStage is evaluated. See Pipeline.select().

Signature:

export declare type SelectStageOptions = StageOptions & {
    selections: Array<Selectable | string>;
};

SetOptions

An options object that configures the behavior of setDoc(), and calls. These calls can be configured to perform granular merges instead of overwriting the target documents in their entirety by providing a SetOptions with merge: true.

Signature:

export declare type SetOptions = {
    readonly merge?: boolean;
} | {
    readonly mergeFields?: Array<string | FieldPath>;
};

SortStageOptions

Options defining how a SortStage is evaluated. See Pipeline.sort().

Signature:

export declare type SortStageOptions = StageOptions & {
    orderings: Ordering[];
};

StageOptions

Options defining how a Stage is evaluated.

Signature:

export declare type StageOptions = {
    rawOptions?: {
        [name: string]: unknown;
    };
};

SubcollectionStageOptions

Options defining how a SubcollectionStage is evaluated.

Signature:

export declare type SubcollectionStageOptions = StageOptions & {
    path: string;
};

TimeGranularity

Specify time granularity for expressions.

Signature:

export declare type TimeGranularity = TimeUnit | 'week' | 'week(monday)' | 'week(tuesday)' | 'week(wednesday)' | 'week(thursday)' | 'week(friday)' | 'week(saturday)' | 'week(sunday)' | 'isoweek' | 'month' | 'quarter' | 'year' | 'isoyear';

TimePart

Specify time parts for timestampExtract expressions.

Signature:

export declare type TimePart = TimeGranularity | 'dayofweek' | 'dayofyear';

TimeUnit

Specify time units for expressions.

Signature:

export declare type TimeUnit = 'microsecond' | 'millisecond' | 'second' | 'minute' | 'hour' | 'day';

UnionStageOptions

Options defining how a UnionStage is evaluated. See Pipeline.union().

Signature:

export declare type UnionStageOptions = StageOptions & {
    other: Pipeline;
};

UnnestStageOptions

Represents the specific options available for configuring an UnnestStage within a pipeline.

Signature:

export declare type UnnestStageOptions = StageOptions & {
    selectable: Selectable;
    indexField?: string;
};

WhereStageOptions

Options defining how a WhereStage is evaluated. See Pipeline.where().

Signature:

export declare type WhereStageOptions = StageOptions & {
    condition: BooleanExpression;
};

WithFieldValue

Allows FieldValues to be passed in as a property value while maintaining type safety.

Signature:

export declare type WithFieldValue<T> = T | (T extends Primitive ? T : T extends {} ? {
    [K in keyof T]: WithFieldValue<T[K]> | FieldValue;
} : never);