$firstN (aggregation accumulator)
On this page本页内容
Definition定义
$firstN
New in version 5.2.5.2版新增。Returns an aggregation of the first返回一个组中前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,$firstN
returns all elements in the group.n
个,$firstN
将返回该组中的所有元素。
Syntax语法
{
$firstN:
{
input: <expression>,
n: <expression>
}
}
input
specifies the field(s) from the document to take the first指定文档中要获取的第一个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
.$group
的_id
值。For details see group key example.有关详细信息,请参阅组键示例。
Behavior行为
Null and Missing ValuesNull
值和缺失值
$firstN
does not filter out null values.不筛选空值。$firstN
converts missing values to null.将缺少的值转换为null
。
Consider the following aggregation that returns the first 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",
firstFiveScores:
{
$firstN:
{
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
.gameId
,G1
。PlayerD
has a missing score and缺少PlayerE
has a nullscore
. These values are both considered as null.score
,PlayerE
的score
为空。这两个值都被视为null
。ThefirstFiveScores
field is specified usinginput : "$score"
and returned as an array.firstFiveScores
字段是使用input : "$score"
指定的,并以数组的形式返回。Since there is no sort criteria the first 5由于没有排序标准,返回前5个score
fields are returned.score
字段。
[
{
_id: 'G1',
firstFiveScores: [ 1, 2, 3, null, null ]
}
]
Comparison of $firstN
and $topN
Accumulators$firstN
和$topN
累加器的比较
$firstN
and $topN
AccumulatorsBoth $firstN
and $topN
accumulators can accomplish similar results.$firstN
和$topN
累加器都可以实现类似的结果。
In general:一般而言:
If the documents coming into如果进入$group
are already ordered, you should use$firstN
.$group
的文档已经排序,则应该使用$firstN
。If you're sorting and selecting the top如果要对前n
elements then you can use$topN
to accomplish both tasks with one accumulator.n
个元素进行排序和选择,则可以使用$topN
通过一个累加器来完成这两项任务。$firstN
can be used as an aggregation expression,可以用作聚合表达式,$topN
cannot.$topN
不能。
Restrictions限制
Window Function and Aggregation Expression Support窗口函数和聚合表达式支持
$firstN
is supported as an aggregation expression.支持作为聚合表达式。
For details on aggregation expression usage see Using $firstN as an Aggregation Expression.有关聚合表达式用法的详细信息,请参阅使用$firstN
作为聚合表达式。
$firstN
is supported as a 支持作为窗口运算符。window operator
.
Memory Limit Considerations内存限制注意事项
Aggregation pipelines which call 调用$firstN
are subject to the 100 MB limit. If this limit is exceeded for an individual group, the aggregation fails with an error.$firstN
的聚合管道受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 First Three Player Scores for a Single Game查找单场比赛的前三名选手得分
You can use the 您可以使用$firstN
accumulator to find the first three scores in a single game.$firstN
累加器来查找单个游戏中的前三个分数。
db.gamescores.aggregate( [
{
$match : { gameId : "G1" }
},
{
$group:
{
_id: "$gameId",
firstThreeScores:
{
$firstN:
{
input: ["$playerId", "$score"],
n:3
}
}
}
}
] )
The example pipeline:示例管道:
Uses使用$match
to filter the results on a singlegameId
.$match
筛选单个gameId
的结果。In this case,在这种情况下,G1
.G1
。Uses使用$group
to group the results bygameId
. In this case,G1
.$group
按gameId
对结果进行分组。在这种情况下,G1
。Specifies the fields that are input for使用$firstN
withinput : ["$playerId"," $score"]
.input : ["$playerId"," $score"]
指定为$firstN
输入的字段。Uses使用$firstN
to return the first three documents for theG1
game withn : 3
.$firstN
配合n:3
返回G1
游戏的前三个文档。
The operation returns the following results:该操作返回以下结果:
[
{
_id: 'G1',
firstThreeScores: [ [ 'PlayerA', 31 ], [ 'PlayerB', 33 ], [ 'PlayerC', 99 ] ]
}
]
Finding the First Three Player Scores Across Multiple Games在多个游戏中查找前三名玩家的得分
You can use the 您可以使用$firstN
accumulator to find the first n
input fields in each game.$firstN
累加器来查找每个游戏中的前n
个输入字段。
db.gamescores.aggregate( [
{
$group:
{
_id: "$gameId", playerId:
{
$firstN:
{
input: [ "$playerId","$score" ],
n: 3
}
}
}
}
] )
The example pipeline:示例管道:
Uses使用$group
to group the results bygameId
.$group
按gameId
对结果进行分组。Uses使用$firstN
to return the first three documents for each game withn: 3
.$firstN
为每个n:3
的游戏返回前三个文档。Specifies the fields that are input for使用$firstN
withinput : ["$playerId", "$score"]
.input : ["$playerId", "$score"]
指定为$firstN
输入的字段。
The operation returns the following results:该操作返回以下结果:
[
{
_id: 'G1',
playerId: [ [ 'PlayerA', 31 ], [ 'PlayerB', 33 ], [ 'PlayerC', 99 ] ]
},
{
_id: 'G2',
playerId: [ [ 'PlayerA', 10 ], [ 'PlayerB', 14 ], [ 'PlayerC', 66 ] ]
}
]
Using $sort
With $firstN
使用$sort
With$firstN
$sort
With $firstN
Using a 在管道的早期使用$sort
stage earlier in the pipeline can influence the results of the $firstN
accumulator.$sort
阶段可能会影响$firstN
累加器的结果。
In this example:在本例中:
{$sort : { score : -1 } }
sorts the highest scores to the back of each group.将最高分数排序到每组的后面。firstN
returns the three highest scores from front of each group.从每组前面返回三个最高分数。
db.gamescores.aggregate( [
{ $sort : { score : -1 } },
{
$group:
{ _id: "$gameId", playerId:
{
$firstN:
{
input: [ "$playerId","$score" ],
n: 3
}
}
}
}
] )
The operation returns the following results:该操作返回以下结果:
[
{
_id: 'G2',
playerId: [ [ 'PlayerD', 80 ], [ 'PlayerC', 66 ], [ 'PlayerB', 14 ] ]
},
{
_id: 'G1',
playerId: [ [ 'PlayerC', 99 ], [ 'PlayerB', 33 ], [ 'PlayerA', 31 ] ]
}
]
Computing n
Based on the Group Key for $group
基于$Group
的组键计算n
n
Based on the Group Key for $group
You 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:
{
$firstN:
{
input: "$score",
n: { $cond: { if: {$eq: ["$gameId","G2"] }, then: 1, else: 3 } }
}
}
}
}
] )
The example pipeline:示例管道:
Uses使用$group
to group the results bygameId
.$group
按gameId
对结果进行分组。Specifies the fields that input for使用$firstN
withinput : "$score"
.input : "$score"
指定为$firstN
输入的字段。If the如果gameId
isG2
thenn
is 1, otherwisen
is 3.gameId
是G2
,则n
是1
,否则n
是3
。
The operation returns the following results:该操作返回以下结果:
[
{ _id: { gameId: 'G1' }, gamescores: [ 31, 33, 99 ] },
{ _id: { gameId: 'G2' }, gamescores: [ 10 ] }
]
Using $firstN
as an Aggregation Expression使用$firstN
作为聚合表达式
$firstN
as an Aggregation ExpressionYou can also use 您也可以使用$firstN
as an aggregation expression.$firstN
作为聚合表达式。
In this example:在本例中:
$documents
creates the literal document that contains an array of values.创建包含值数组的文本文档。$project
is used to return the output of用于返回$firstN
.$firstN
的输出。使用_id
is omited from the output with_id : 0
._id : 0
则_id
从输出中省略。$firstN
uses the input array of使用[10, 20, 30, 40]
.[10, 20, 30, 40]
的输入数组。The first three elements of the array are returned for the input document.为输入文档返回数组的前三个元素。
db.aggregate( [
{
$documents: [
{ array: [10, 20, 30, 40] } ]
},
{ $project: {
firstThreeElements:{
$firstN:
{
input: "$array",
n: 3
}
}
}
}
] )
The operation returns the following results:该操作返回以下结果:
[
{ firstThreeElements: [ 10, 20, 30 ] }
]