$minN (array operator)

On this page本页内容

Definition定义

$minN

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

Returns the n smallest values in an array.返回数组中的n个最小值。

Tip提示
See also: 参阅:

Syntax语法

$minN has the following syntax:语法如下:

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

Behavior行为

  • You cannot specify a value of n less than 1.不能指定小于1n值。
  • $minN filters out null values found in the input array.筛选出在input数组中找到的null值。
  • If the specified n is greater than or equal to the number of elements in the input array, $minN returns all elements in the input array.如果指定的n大于或等于input数组中的元素数,$minN将返回输入数组中所有元素。
  • If input resolves to a non-array value, the aggregation operation errors.如果input解析为非数组值,则聚合操作出错。
  • If input contains both numeric and string elements, the numeric elements are sorted before string elements according to the BSON comparison order.如果输入同时包含数字和字符串元素,则根据BSON比较顺序,数字元素在字符串元素之前排序。

Example示例

Create a scores collection with the following documents:使用以下文档创建scores集合:

db.scores.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, "2", 3489, 9 ]}
])

The following example uses the $minN operator to retrieve the two lowest scores for each player. 下面的示例使用$minN运算符检索每个玩家的两个最低分数。The lowest scores are returned in the new field minScores created by $addFields.最低分数将返回到$addFields创建的新字段minScores中。

db.scores.aggregate([
   { $addFields: { minScores: { $minN: { n: 2, input: "$score" } } } }
])

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

[{
  "playerId": 1,
  "score": [ 1, 2, 3 ],
  "minScores": [ 1, 2 ]
},
{
  "playerId": 2,
  "score": [ 12, 90, 7, 89, 8 ],
  "minScores": [ 7, 8 ]
},
{
  "playerId": 3,
  "score": [ null ],
  "minScores": [ ]
},
{
  "playerId": 4,
  "score": [ ],
  "minScores": [ ]
},
{
  "playerId": 5,
  "score": [ 1293, "2", 3489, 9 ],
  "minScores": [ 9, 1293 ]
}]
←  $minN (aggregation accumulator)$millisecond (aggregation) →