- Reference >
- Operators >
- Aggregation Pipeline Operators >
- $first (array operator)
$first (array operator)¶
On this page
Definition¶
-
$first¶ New in version 4.4.
Returns the first element in an array.
Note
Disambiguation
This page describes the
$firstarray operator. For the$firstaggregation accumulator, see$first (aggregation accumulator).
See also
Syntax¶
$first has the following syntax:
The <expression> can be any valid expression as long as it resolves to an array,
null or missing. For more information on expressions, see
Expressions.
The $first operator is an alias for the following
$arrayElemAt expression:
Behavior¶
Valid Operands¶
Valid operand for $first must resolve to an array,
null, or missing
- If the operand resolves to a non-empty array,
$firstreturns the first element in the array: - If the operand resolves to an empty array
[],$firstdoes not return a value. - If the operand is null or missing,
$firstreturns null.
For example, create a test collection example1 with the following
documents:
Then, the following adds a new field firstElem whose value is
derived from applying the $first operator to the x
field:
The operator returns the following documents:
Invalid Operands¶
If the operand does not resolve to an array, null, or missing, the aggregation operation as a whole errors.
For example, create a test collection example2 with the following
documents:
Then, the following aggregation operation returns an error because of
the { "_id" : 2, "x" : 2 } document:
That is, the operation returns the following:
Example¶
Create a sample collection runninglog with the following documents:
The following aggregation uses the $first and
$last operator on the log array to retrieve the
information for the first run and the last run:
The operation returns the following results:
To calculate the change between the first and the last distances, the
following operation uses $cond and $size
operators to calculate the difference (i.e. $subtract)
the two distances if there are two or more elements in the log
array:
The operation returns the following documents:
By default, mongosh uses the 64-bit floating-point
double for numbers. To improve precision, you can use NumberDecimal
instead.