$firstN (array operator)
On this page本页内容
Definition定义
$firstN
New in version 5.2.5.2版新增。Returns a specified number of elements from the beginning of an array.从数组的开头返回指定数量的元素。
Tip
See also: 另请参阅:
Syntax语法
$firstN
has the following syntax:具有以下语法:
{ $firstN: { n: <expression>, input: <expression> } }
n | $firstN returns.$firstN 返回的数组元素数。 |
input | 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 than1
.1
的n
值。If the specified如果指定的n
is greater than or equal to the number of elements in theinput
array,$firstN
returns theinput
array.n
大于或等于input
数组中的元素数,$firstN
将返回输入数组。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, NumberLong("2090845886852"), 23 ]}
])
The following example uses the 以下示例使用$firstN
operator to retrieve the first three scores for each player. The scores are returned in the new field firstScores
created by $addFields
.$firstN
运算符来检索每个玩家的前三个分数。分数在$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, NumberLong("2090845886852"), 23 ],
"firstScores": [ "12.1", 2, NumberLong("2090845886852") ]
}]