- Reference >
- Operators >
- Aggregation Pipeline Operators >
- $last (aggregation)
$last (aggregation)¶
On this page
Definition¶
-
$last
¶ New in version 4.4.
Returns the last element in an array.
Disambiguation
The following page describes the array element operator
$last
. For the accumulator$last
, available only with the$group
stage, see$last (accumulator)
instead.
Syntax¶
The $last
operator 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 $last
operator is an alias for the following
$arrayElemAt
expression:
Behavior¶
Valid Operands¶
Valid operand for $last
must resolve to an array, null,
or missing.
- If the operand resolves to a non-empty array,
$last
returns the first element in the array: - If the operand resolves to an empty array
[]
,$last
does not return a value. - If the operand is null or missing,
$last
returns null.
For example, create a test collection example1
with the following
documents:
Then, the following adds a new field lastElem
whose value is
derived from applying the $last
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, the shell
uses the 64-bit floating-point
double for numbers. To improve precision, you can use NumberDecimal
instead.