Docs HomeMongoDB Manual

$lastN (aggregation accumulator)

Definition定义

$lastN

New in version 5.2. 5.2版新增。

Returns an aggregation of the last n elements within a group. 返回一个组中最后n个元素的聚合。The elements returned are meaningful only if in a specified sort order. 只有在指定的排序顺序中,返回的元素才有意义。If the group contains fewer than n elements, $lastN returns all elements in the group.如果该组包含的元素少于n个,$lastN将返回该组中的所有元素。

Syntax语法

{
$lastN:
{
input: <expression>,
n: <expression>
}
}
  • input specifies the field(s) from the document to take the last n of. Input can be any expression.指定文档中要取最后n的字段。输入可以是任何表达式。
  • n has to be a positive integral expression that is either a constant or depends on the _id value for $group. For details see group key example.必须是一个正整数表达式,该表达式要么是常数,要么取决于$group_id值。有关详细信息,请参阅组键示例

Behavior行为

Null and Missing Values空值和缺失值

  • $lastN does not filter out null values.不筛选空值。
  • $lastN converts missing values to null.将缺少的值转换为null

Consider the following aggregation that returns the last five documents from a group:考虑以下从一个组返回最后五个文档的聚合:

db.aggregate( [
{
$documents: [
{ playerId: "PlayerA", gameId: "G1", score: 1 },
{ playerId: "PlayerB", gameId: "G1", score: 2 },
{ playerId: "PlayerC", gameId: "G1", score: 3 },
{ playerId: "PlayerD", gameId: "G1"},
{ playerId: "PlayerE", gameId: "G1", score: null }
]
},
{
$group:
{
_id: "$gameId",
lastFiveScores:
{
$lastN:
{
input: "$score",
n: 5
}
}
}
}
] )

In this example:在本例中:

  • $documents creates the literal documents that contain player scores.创建包含玩家分数的文字文档。
  • $group groups the documents by gameId. gameId对文档进行分组。This example has only one gameId, G1.这个例子只有一个gameIdG1
  • PlayerD has a missing score and PlayerE has a null score. 缺少score,而PlayerEscore为空。These values are both considered as null.这两个值都被视为null
  • The lastFiveScores field is specified using input : "$score" and returned as an array.lastFiveScores字段是使用input : "$score"指定的,并作为数组返回。
  • Since there is no sort criteria the last 5 score fields are returned.由于没有排序标准,因此返回最后5个score字段。
[
{
_id: "G1",
lastFiveScores: [ 1, 2, 3, null, null ]
}
]

Comparison of $lastN and $bottomN$lastN$bottomN的比较

Both $lastN and $bottomN accumulators can accomplish similar results.$lastN$bottomN累加器都可以实现类似的结果。

In general:一般来说

  • If the documents coming into $group are already ordered, you should use $lastN.如果进入$group的文档已经排序,则应该使用$lastN
  • If you're sorting and selecting the bottom n elements then you can use $bottomN to accomplish both tasks with one accumulator.如果您要排序并选择最下面的n个元素,那么您可以使用$bottomN来用一个累加器完成这两个任务。
  • $lastN can be used as an aggregation expression, $bottomN cannot.可以用作聚合表达式,$bottomN不能。

Restrictions限制

Window Function and Aggregation Expression Support窗口函数和聚合表达式支持

$lastN is supported as an aggregation expression.支持作为聚合表达式

For details on aggregation expression usage see Using $lastN as an Aggregation Expression.有关聚合表达式用法的详细信息,请参阅使用$lastN作为聚合表达式

$lastN is supported as a window operator.支持作为窗口运算符

Memory Limit Considerations内存限制注意事项

Aggregation pipelines which call $lastN are subject to the 100 MB limit. If this limit is exceeded for an individual group, the aggregation fails with an error.调用$lastN的聚合管道受100MB限制。如果单个组超过此限制,则聚合将失败并出现错误。

Examples实例

Consider a gamescores collection with the following documents:考虑一个包含以下文档的gamescores集合:

db.gamescores.insertMany([
{ playerId: "PlayerA", gameId: "G1", score: 31 },
{ playerId: "PlayerB", gameId: "G1", score: 33 },
{ playerId: "PlayerC", gameId: "G1", score: 99 },
{ playerId: "PlayerD", gameId: "G1", score: 1 },
{ playerId: "PlayerA", gameId: "G2", score: 10 },
{ playerId: "PlayerB", gameId: "G2", score: 14 },
{ playerId: "PlayerC", gameId: "G2", score: 66 },
{ playerId: "PlayerD", gameId: "G2", score: 80 }
])

Find the Last Three Player Scores for a Single Game查找单个游戏的最后三名玩家得分

You can use the $lastN accumulator to find the last three scores in a single game.您可以使用$lastN累加器来查找单个游戏中的最后三个分数。

db.gamescores.aggregate( [
{
$match : { gameId : "G1" }
},
{
$group:
{
_id: "$gameId",
lastThreeScores:
{
$lastN:
{
input: ["$playerId", "$score"],
n:3
}
}
}
}
] )

The example pipeline:示例管道:

  • Uses $match to filter the results on a single gameId. In this case, G1.使用$match筛选单个gameId的结果。在这种情况下,为G1
  • Uses $group to group the results by gameId. In this case, G1.使用$groupgameId对结果进行分组。在这种情况下为G1
  • Specifies the fields that are output from $lastN with output : ["$playerId"," $score"].使用output : ["$playerId"," $score"]指定从$lastN输出的字段。
  • Uses $lastN to return the last three documents for the G1 game with n : 3.使用$lastNn:3返回G1游戏的最后三个文档。

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

[
{
_id: "G1",
lastThreeScores: [ [ "PlayerB", 33 ], [ "PlayerC", 99 ], [ "PlayerD", 1 ] ]
}
]

Finding the Last Three Player Scores Across Multiple Games在多个游戏中查找最后三名玩家的得分

You can use the $lastN accumulator to find the last n input fields in each game.您可以使用$lastN累加器来查找每个游戏中的最后n个输入字段。

db.gamescores.aggregate( [
{
$group:
{
_id: "$gameId", playerId:
{
$lastN:
{
input: [ "$playerId","$score" ],
n: 3
}
}
}
}
] )

The example pipeline:示例管道:

  • Uses $group to group the results by gameId.使用$groupgameId对结果进行分组。
  • Uses $lastN to return the last three documents for each game with n: 3.使用$lastN以及n:3为每个的游戏返回最后三个文档。
  • Specifies the fields that are input for $lastN with input : ["$playerId", "$score"].使用input : ["$playerId", "$score"]指定$lastN的输入字段。

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

[
{
_id: 'G2',
playerId: [ [ 'PlayerB', 14 ], [ 'PlayerC', 66 ], [ 'PlayerD', 80 ] ]
},
{
_id: 'G1',
playerId: [ [ 'PlayerB', 33 ], [ 'PlayerC', 99 ], [ 'PlayerD', 1 ] ]
}
]

Using $sort With $lastN使用$sort配合$lastN

Using a $sort stage earlier in the pipeline can influence the results of the $lastN accumulator.在管道的早期使用$sort阶段可能会影响$lastN累加器的结果。

In this example:在本例中:

  • {$sort : { score : -1 } } sorts the highest scores to the back of each group.将最高分数排序到每组的后面。
  • lastN returns the three lowest scores from the back of each group.返回每组后面的三个最低分数。
db.gamescores.aggregate( [
{ $sort : { score : -1 } },
{

$group:
{ _id: "$gameId", playerId:
{
$lastN:
{
input: [ "$playerId","$score" ],
n: 3
}
}
}
}
] )

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

[
{
_id: 'G2',
playerId: [ [ 'PlayerC', 66 ], [ 'PlayerB', 14 ], [ 'PlayerA', 10 ] ]
},
{
_id: 'G1',
playerId: [ [ 'PlayerB', 33 ], [ 'PlayerA', 31 ], [ 'PlayerD', 1 ] ]
}
]

Computing n Based on the Group Key for $group基于$group的组键计算n

You can also assign the value of n dynamically. 您也可以动态地指定n的值。In this example, the $cond expression is used on the gameId field.在本例中,$cond表达式用于gameId字段。

db.gamescores.aggregate([
{
$group:
{
_id: {"gameId": "$gameId"},
gamescores:
{
$lastN:
{
input: "$score",
n: { $cond: { if: {$eq: ["$gameId","G2"] }, then: 1, else: 3 } }
}
}
}
}
] )

The example pipeline:示例管道:

  • Uses $group to group the results by gameId.使用$groupgameId对结果进行分组。
  • Specifies the fields that input for $lastN with input : "$score".指定使用input : "$score"$lastN输入的字段。
  • If the gameId is G2 then n is 1, otherwise n is 3.如果gameIdG2,则n是1,否则n是3。

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

[
{ _id: { gameId: "G1" }, gamescores: [ 33, 99, 1 ] },
{ _id: { gameId: "G2" }, gamescores: [ 80 ] }
]

Using $lastN as an Aggregation Expression使用$lastN作为聚合表达式

You can also use $lastN as an aggregation expression.您也可以使用$lastN作为聚合表达式。

In this example:在本例中:

  • $documents creates the literal document that contains an array of values.创建包含值数组的文字文档。
  • $project is used to return the output of $lastN.用于返回$lastN的输出。
  • _id is omited from the output with _id : 0.使用_id : 0从输出中省略掉_id
  • $lastN uses the input array of [10, 20, 30, 40].使用[10, 20, 30, 40]的输入数组。
  • The last three elements of the array are returned for the input document.为输入文档返回数组的最后三个元素。
db.aggregate( [
{
$documents: [
{ array: [10, 20, 30, 40] } ]
},
{ $project: {
lastThreeElements:{
$lastN:
{
input: "$array",
n: 3
}
}
}
}
] )

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

[ { lastThreeElements: [ 20, 30, 40 ] } ]