Database Manual / Reference / Query Language / Accumulators

$firstN (expression operator)(表达式运算符)

Definition定义

New in version 5.2.在版本5.2中新增。

$firstN can be used as an aggregation accumulator or array operator. As an aggregation accumulator, it returns an aggregation of the first n elements within a group. As an array operator, it returns the specified number of elements from the beginning of an array.可以用作聚合累加器或数组运算符。作为聚合累加器,它返回组内前n个元素的聚合。作为数组运算符,它从数组的开头返回指定数量的元素。

Aggregation Accumulator聚合累加器

$firstN

When $firstN 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, $firstN returns all elements in the group.$firstN用作聚合累加器时,返回的元素只有在指定的排序顺序下才有意义。如果组包含的元素少于n个,$firstN将返回组中的所有元素。

Syntax语法

When used as an aggregation accumulator, $firstN has the following syntax:当用作聚合累加器时,$firstN具有以下语法:

{
$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.不筛选null值。
  • $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. This example has only one gameId, G1.gameId对文档进行分组。这个例子只有一个gameId G1
  • PlayerD has a missing score and PlayerE has a null score. 缺少score,而PlayerEscore为空。These values are both considered as null.这些值都被视为null
  • The firstFiveScores field is specified using input : "$score" and returned as an array.firstFiveScores字段使用input : "$score"指定,并作为数组返回。
  • Since there is no sort criteria the first 5 score fields are returned.由于没有排序标准,因此返回前5个score字段。
[
{
_id: 'G1',
firstFiveScores: [ 1, 2, 3, null, null ]
}
]

Comparison of $firstN and $topN Accumulators$firstN$topN累加器的比较

Both $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.$firstN可以用作聚合表达式,$topN不能。

Restrictions限制

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

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

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

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 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 input for $firstN with input : ["$playerId"," $score"].通过input : ["$playerId"," $score"]指定为$firstN输入的字段。
  • Uses $firstN to return the first three documents for the G1 game with n : 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 by gameId.使用$groupgameId对结果进行分组。
  • Uses $firstN to return the first three documents for each game with n: 3.使用$firstN配合n:3返回每个游戏的前三个文档。
  • Specifies the fields that are input for $firstN with input : ["$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$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

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 by gameId.使用$groupgameId对结果进行分组。
  • Specifies the fields that input for $firstN with input : "$score".使用input : "$score"$firstN指定输入的字段。
  • If the gameId is G2 then n is 1, otherwise n is 3.如果gameIdG2,则n1,否则n3

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作为聚合表达式

You 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 ] }
]

Array Operator数组运算符

$firstN

Syntax语法

When used as an array operator, $firstN has the following syntax:当用作数组运算符时,$firstN具有以下语法:

{ $firstN: { n: <expression>, input: <expression> } }
Field字段Description描述
nAn expression that resolves to a positive integer. The integer specifies the number of array elements that $firstN returns.解析为正整数的表达式。整数指定$firstN返回的数组元素的数量。
inputAn expression that resolves to the array from which to return n elements.一个表达式,解析为从中返回n个元素的数组。

Behavior行为

  • $firstN returns elements in the same order they appear in the input array.返回元素在输入数组中出现的顺序。
  • $firstN does not filter out null values in the input array.不会筛选掉输入数组中的null值。
  • You cannot specify a value of n less than 1.不能指定小于1n值。
  • If the specified n is greater than or equal to the number of elements in the input array, $firstN returns the input array.如果指定的n大于或等于input数组中的元素数,则$firstN返回input数组。
  • If input resolves 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 $firstN operator to retrieve the first three scores for each player. 以下示例使用$firstN运算符检索每个玩家的前三个分数。The scores are returned in the new field firstScores created by $addFields.分数在$addFields创建的新字段firstScores中返回。

db.games.aggregate([
{ $addFields: { firstScores: { $firstN: { n: 3, input: "$score" } } } }
])

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

[{
"playerId": 1,
"score": [ 1, 2, 3 ],
"firstScores": [ 1, 2, 3 ]
},
{
"playerId": 2,
"score": [ 12, 90, 7, 89, 8 ],
"firstScores": [ 12, 90, 7 ]
},
{
"playerId": 3,
"score": [ null ],
"firstScores": [ null ]
},
{
"playerId": 4,
"score": [ ],
"firstScores": [ ]
},
{
"playerId": 5,
"score": [ 1293, null, 3489, 9 ],
"firstScores": [ 1293, null, 3489 ]
},
{
"playerId": 6,
"score": [ "12.1", 2, Long("2090845886852"), 23 ],
"firstScores": [ "12.1", 2, Long("2090845886852") ]
}]