On this page本页内容
$first
¶New in version 4.4.版本4.4中的新功能。
Returns the first element in an array.返回数组中的第一个元素。
Disambiguation消除歧义
The following page describes the array element operator 下一页介绍数组元素运算符$first
. $first
。For the accumulator 对于仅适用于$first
, available only with the $group
stage, see $first (accumulator)
instead.$group
阶段的累加器$first
,请参阅$first
(累加器)。
See also参阅
$first
has the following syntax:$first
语法如下所示:
The <expression>
can be any valid expression as long as it resolves to an array, null or missing. <expression>
可以是任何有效的表达式,只要它解析为数组(null
或缺失)。For more information on expressions, see Expressions.有关表达式的详细信息,请参阅表达式。
The $first
operator is an alias for the following $arrayElemAt
expression:$first
运算符是以下$arrayElemAt
表达式的别名:
Valid operand for $first
must resolve to an array, null, or missing$first
的有效操作数必须解析为数组、null
或缺失
$first
returns the first element in the array:$first
返回数组中的第一个元素:[]
, $first
does not return a value.[]
,$first
不返回值。$first
returns null.null
或缺少,$first
返回null
。For example, create a test collection 例如,使用以下文档创建测试集合example1
with the following documents:example1
:
Then, the following adds a new field 然后,下面添加一个新字段firstElem
whose value is derived from applying the $first
operator to the x
field:firstElem
,其值是通过将$first
运算符应用于x
字段得到的:
The operator returns the following documents:运算符返回以下文件:
If the operand does not resolve to an array, null, or missing, the aggregation operation as a whole errors.如果操作数未解析为数组、null
或缺失,则整个聚合操作将出错。
For example, create a test collection 例如,使用以下文档创建测试集合example2
with the following documents:example2
:
Then, the following aggregation operation returns an error because of the 然后,由于{ "_id" : 2, "x" : 2 }
document:{ "_id" : 2, "x" : 2 }
文档,以下聚合操作返回一个错误:
That is, the operation returns the following:也就是说,该操作返回以下内容:
Create a sample collection 使用以下文档创建样本集合runninglog
with the following documents:runninglog
:
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:$first
和$last
运算符来检索第一次运行和最后一次运行的信息:
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:$cond
和$size
运算符来计算两个距离之间的差异(即,如果log
数组中有两个或多个元素,则使用$subtract
):
The operation returns the following documents:该操作将返回以下文档:
By default, the 默认情况下,shell
uses the 64-bit floating-point double for numbers. shell
对数字使用64位浮点双精度。To improve precision, you can use NumberDecimal instead.为了提高精度,可以改用NumberDecimal。