$last (aggregation accumulator)(聚合累加器)

On this page本页内容

Definition定义

$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(数组运算符)

Syntax语法

$last has the following syntax:语法如下所示:

{ $last: <expression> }

For more information on expressions, see Expressions.有关表达式的详细信息,请参阅表达式

Behavior行为

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阶段之后,以使输入文档按定义的顺序排列。

Note

Although the $sort stage passes ordered documents as input to the $group stage, $group is not guaranteed to maintain this sort order in its own output.尽管$sort阶段将已排序的文档作为输入传递给$group阶段,但$group不保证在其自身的输出中保持这种排序顺序。

Example示例

Consider a sales collection with the following documents:考虑一个sales集合带有以下文档:

{ "_id" : 1, "item" : "abc", "date" : ISODate("2014-01-01T08:00:00Z"), "price" : 10, "quantity" : 2 }
{ "_id" : 2, "item" : "jkl", "date" : ISODate("2014-02-03T09:00:00Z"), "price" : 20, "quantity" : 1 }
{ "_id" : 3, "item" : "xyz", "date" : ISODate("2014-02-03T09:05:00Z"), "price" : 5, "quantity" : 5 }
{ "_id" : 4, "item" : "abc", "date" : ISODate("2014-02-15T08:00:00Z"), "price" : 10, "quantity" : 10 }
{ "_id" : 5, "item" : "xyz", "date" : ISODate("2014-02-15T09:05:00Z"), "price" : 5, "quantity" : 10 }
{ "_id" : 6, "item" : "xyz", "date" : ISODate("2014-02-15T12:05:10Z"), "price" : 5, "quantity" : 5 }
{ "_id" : 7, "item" : "xyz", "date" : ISODate("2014-02-15T14:12:12Z"), "price" : 5, "quantity" : 10 }

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:以下操作首先按itemdate对文档进行排序,然后在下面的$group阶段中,按item字段对现在排序的文档进行分组,并使用$last累加器计算每个项目的最后销售日期:

db.sales.aggregate(
   [
     { $sort: { item: 1, date: 1 } },
     {
       $group:
         {
           _id: "$item",
           lastSalesDate: { $last: "$date" }
         }
     }
   ]
)

The operation returns the following results:操作返回以下结果:

{ "_id" : "xyz", "lastSalesDate" : ISODate("2014-02-15T14:12:12Z") }
{ "_id" : "jkl", "lastSalesDate" : ISODate("2014-02-03T09:00:00Z") }
{ "_id" : "abc", "lastSalesDate" : ISODate("2014-02-15T08:00:00Z") }