$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> } }
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.不能指定n小于1的值。
  • 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, NumberLong("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, NumberLong("2090845886852"), 23 ],
  "firstScores": [ "12.1", 2, NumberLong("2090845886852") ]
 }]
←  $first (array operator)$floor (aggregation) →