Database Manual / Reference / Query Language / Expressions

$maxN (acumulator operator)(累加器运算符)

Definition定义

$maxN

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

Returns the n largest values in an array.返回数组中n个最大值。

Tip

$minN

Syntax语法

$maxN has the following syntax:具有以下语法:

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

Behavior行为

  • You cannot specify a value of n less than 1.不能指定小于1n值。
  • $maxN filters out null values found in the input array.$maxN筛选掉输入数组中的null值。
  • If the specified n is greater than or equal to the number of elements in the input array, $maxN returns all elements in the input array.如果指定的n大于或等于input数组中的元素数,则$maxN将返回输入数组中所有的元素。
  • If input resolves to a non-array value, the aggregation operation errors.如果input解析为非数组值,则聚合操作将出错。
  • If input contains both numeric and string elements, the string elements are sorted before numeric elements according to the BSON comparison order.如果input包含数字和字符串元素,则根据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 $maxN operator to retrieve the two highest scores for each player. 以下示例使用$maxN运算符检索每个玩家的两个最高分数。The highest scores are returned in the new field maxScores created by $addFields.最高分数在$addFields创建的新字段maxScores中返回。

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

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

[{
"playerId": 1,
"score": [ 1, 2, 3 ],
"maxScores": [ 3, 2 ]
},
{
"playerId": 2,
"score": [ 12, 90, 7, 89, 8 ],
"maxScores": [ 90, 89 ]
},
{
"playerId": 3,
"score": [ null ],
"maxScores": [ ]
},
{
"playerId": 4,
"score": [ ],
"maxScores": [ ]
},
{
"playerId": 5,
"score": [ 1293, "2", 3489, 9 ],
"maxScores": [ "2", 3489 ]
}]