Definition定义
New in version 5.2.在版本5.2中新增。
$lastN can be used as an aggregation accumulator or array operator. As an aggregation accumulator, it an aggregation of the last 可以用作聚合累加器或数组运算符。作为聚合累加器,它是组内最后n elements within a group. As an array operator, it returns the specified number of elements from the end of an array.n个元素的聚合。作为数组运算符,它从数组末尾返回指定数量的元素。
Aggregation Accumulator聚合累加器
$lastN
When 当$lasttN is used as an aggregation accumulator, the elements returned are meaningful only if they are in a specified sort order. If the group contains fewer than n elements, $lastN returns all elements in the group.$lasttN用作聚合累加器时,返回的元素只有按照指定的排序顺序才有意义。如果组包含的元素少于n个,$lastN将返回组中的所有元素。
Syntax语法
{
$lastN:
{
input: <expression>,
n: <expression>
}
}
inputspecifies the field(s) from the document to take the last指定文档中要取最后nof. Input can be any expression.n的字段。输入可以是任何表达式。nhas to be a positive integral expression that is either a constant or depends on the_idvalue for$group. For details see group key example.n必须是一个正积分表达式,它要么是一个常数,要么取决于$group的_id值。有关详细信息,请参阅组键示例。
Behavior行为
Null and Missing Valuesnull值和缺失值
$lastNdoes not filter out null values.不筛选null值。$lastNconverts 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:在这个例子中:
$documentscreates the literal documents that contain player scores.创建包含玩家分数的文字文档。$groupgroups the documents bygameId. This example has only onegameId,G1.$group按gameId对文档进行分组。这个例子只有一个gameIdG1。PlayerDhas a missing score andPlayerEhas a nullscore. These values are both considered as null.PlayerD缺少分数,PlayerE的分数为空。这些值都被视为null。ThelastFiveScoresfield is specified usinginput : "$score"and returned as an array.lastFiveScores字段使用input : "$score"指定,并以数组形式返回。Since there is no sort criteria the last 5由于没有排序标准,因此返回最后5个scorefields are returned.score字段。
[
{
_id: "G1",
lastFiveScores: [ 1, 2, 3, null, null ]
}
]Comparison of $lastN and $bottomN$lastN和$bottomN的比较
$lastN and $bottomNBoth $lastN and $bottomN accumulators can accomplish similar results.$lastN和$bottomN累加器都可以实现类似的结果。
In general:一般来说:
If the documents coming into如果进入$groupare already ordered, you should use$lastN.$group的文档已经订购,则应使用$lastN。If you're sorting and selecting the bottom如果你正在排序和选择底部的nelements then you can use$bottomNto accomplish both tasks with one accumulator.n个元素,那么你可以使用$bottomN用一个累加器来完成这两个任务。$lastNcan be used as an aggregation expression,$bottomNcannot.$lastN可以用作聚合表达式,而$bottomN不能。
Restrictions限制
Window Function and Aggregation Expression Support窗口函数和聚合表达式支持
支持$lastN is supported as an aggregation expression.$lastN作为聚合表达式。
支持$lastN is supported as a window operator.$lastN作为窗口运算符。
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使用$matchto filter the results on a singlegameId. In this case,G1.$match筛选单个gameId的结果。在这种情况下,G1。Uses使用$groupto group the results bygameId. In this case,G1.$group按gameId对结果进行分组。在这种情况下,G1。Specifies the fields that are output from使用$lastNwithoutput : ["$playerId"," $score"].output : ["$playerId"," $score"]指定从$lastN输出的字段。Uses使用$lastNto return the last three documents for theG1game withn : 3.$lastN配合n: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使用$groupto group the results bygameId.$group按gameId对结果进行分组。Uses使用$lastNto return the last three documents for each game withn: 3.$lastN配合n:3返回每个游戏的最后三个文档。Specifies the fields that are input for使用$lastNwithinput : ["$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
$sort With $lastNUsing 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.将最高分数排序到每组的后面。lastNreturns 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
n Based on the Group Key for $groupYou can also assign the value of 您还可以动态地分配n dynamically. In this example, the $cond expression is used on the gameId field.n的值。在这个例子中,$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使用$groupto group the results bygameId.$group按gameId对结果进行分组。Specifies the fields that input for使用$lastNwithinput : "$score".input : "$score"指定为$lastN输入的字段。If the如果gameIdisG2thennis 1, otherwisenis 3.gameId为G2,则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作为聚合表达式
$lastN as an Aggregation ExpressionYou can also use 您还可以将$lastN as an aggregation expression.$lastN用作聚合表达式。
In this example:在这个例子中:
$documentscreates the literal document that contains an array of values.创建包含值数组的文本文档。$projectis used to return the output of用于返回$lastN.$lastN的输出。_idis omited from the output with从_id : 0._id : 0的输出中省略。$lastNuses 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 ] } ]Array Operator数组运算符
$lastN
Syntax语法
$lastN has the following syntax:具有以下语法:
{ $lastN: { n: <expression>, input: <expression> } }
n | $lastN returns.$lastN返回的数组元素的数量。 |
input | n elements.n个元素的数组。 |
Behavior行为
$lastNreturns elements in the same order they appear in the input array.返回元素在输入数组中出现的顺序。$lastNdoes not filter outnullvalues in the input array.$lastN不会筛选掉输入数组中的null值。You cannot specify a value of不能指定小于nless than1.1的n值。If the specified如果指定的nis greater than or equal to the number of elements in theinputarray,$lastNreturns theinputarray.n大于或等于input数组中的元素数,则$lastN返回输入数组。If如果inputresolves to a non-array value, the aggregation operation errors.input解析为非数组值,则聚合操作将出错。
Example示例
The collection 集合games has the following documents:games有以下文件:
db.games.insertMany([
{ "playerId" : 1, "score" : [ 1, 2, 3 ] },
{ "playerId" : 2, "score" : [ 12, 90, 7, 89, 8 ] },
{ "playerId" : 3, "score" : [ null ] },
{ "playerId" : 4, "score" : [ ] },
{ "playerId" : 5, "score" : [ 1293, null, 3489, 9 ]},
{ "playerId" : 6, "score" : [ "12.1", 2, Long("2090845886852"), 23 ]}
])
The following example uses the 以下示例使用$lastN operator to retrieve the last three scores for each player. The scores are returned in the new field lastScores created by $addFields.$lastN运算符检索每个玩家的最后三个分数。分数在$addFields创建的新字段lastScores中返回。
db.games.aggregate([
{ $addFields: { lastScores: { $lastN: { n: 3, input: "$score" } } } }
])
The operation returns the following results:该操作返回以下结果:
[{
"playerId": 1,
"score": [ 1, 2, 3 ],
"lastScores": [ 1, 2, 3 ]
},
{
"playerId": 2,
"score": [ 12, 90, 7, 89, 8 ],
"lastScores": [ 7, 89, 8 ]
},
{
"playerId": 3,
"score": [ null ],
"lastScores": [ null ]
},
{
"playerId": 4,
"score": [ ],
"lastScores": [ ]
},
{
"playerId": 5,
"score": [ 1293, null, 3489, 9 ],
"lastScores": [ null, 3489, 9 ]
},
{
"playerId": 6,
"score": [ "12.1", 2, Long("2090845886852"), 23 ],
"lastScores": [ 2, Long("2090845886852"), 23 ]
}]