On this page本页内容
$last
¶Returns the value that results from applying an expression to the last document in a group of documents that share the same group by a field. 返回将表达式应用于按字段共享同一组的文档组中的最后一个文档所产生的值。Only meaningful when documents are in a defined order.仅当文档按定义的顺序排列时才有意义。
$last
is only available in the 仅在$group
stage.$group
阶段可用。
Disambiguation消除歧义
The following page describes the accumulator 下一页介绍了累加器$last
, available only within the $group
stage. $last
,它仅在$group
阶段中可用。For the array operator 有关数组运算符$last
, see $last (array operator)
instead.$last
,请参阅$last
(数组运算符)。
$last
has the following syntax:语法如下所示:
For more information on expressions, see Expressions.有关表达式的详细信息,请参阅表达式。
When using 在$last
in a $group
stage, the $group
stage should follow a $sort
stage to have the input documents in a defined order.$group
阶段中使用$last
时,$group
阶段应该在$sort
阶段之后,以使输入文档按定义的顺序排列。
Consider a 考虑一个sales
collection with the following documents:sales
集合带有以下文档:
The following operation first sorts the documents by 以下操作首先按item
and date
, and then in the following $group
stage, groups the now sorted documents by the item
field and uses the $last
accumulator to compute the last sales date for each item:item
和date
对文档进行排序,然后在下面的$group
阶段中,按item
字段对现在排序的文档进行分组,并使用$last
累加器计算每个项目的最后销售日期:
The operation returns the following results:操作返回以下结果: