On this page本页内容
$lastN
New in version 5.2.在版本5.2中新增。
Returns a specified number of elements from the end of an array.从数组末尾返回指定数量的元素。
$lastN has the following syntax:语法如下:
{ $lastN: { n: <expression>, input: <expression> } }
n | $lastN returns.$lastN返回的数组元素数。
|
input | n elements.n个元素的数组的表达式。
|
$lastN$lastNnull values in the input array.null值。n less than 1.n小于1的值。n is greater than or equal to the number of elements in the input array, $lastN returns the input array.n大于或等于input数组中的元素数,$lastN将返回input数组。input resolves to a non-array value, the aggregation operation errors.input解析为非数组值,则聚合操作出错。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, NumberLong("2090845886852"), 23 ]}
])
The following example uses the 下面的示例使用$lastN operator to retrieve the last three scores for each player. $lastN运算符检索每个玩家的最后三个分数。The scores are returned in the new field 分数将返回到lastScores created by $addFields.$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, NumberLong("2090845886852"), 23 ],
"lastScores": [ 2, NumberLong("2090845886852"), 23 ]
}]