文档菜单
文档首页
/
MongoDB 手册
/ / /

$maxN(数组操作符)

本页

  • 定义
  • 语法
  • 行为
  • 示例
$maxN

版本5.2.

返回数组中的前n个最大值。

提示

另请参阅

最小N

$maxN具有以下语法

{ $maxN: { n: <expression>, input: <expression> } }
字段
描述
n
一个解析为正整数的表达式。整数指定了$maxN返回的数组元素数量。
input
一个解析为数组的表达式,从该数组返回最大的n个元素。
  • 不能指定小于 1n 值。

  • $maxN 过滤出在 input 数组中找到的 null 值。

  • 如果指定的 n 大于或等于 input 数组中的元素数量,$maxN 返回 input 数组中的所有元素。

  • 如果 input 解析为非数组值,聚合操作会出错。

  • 如果 input 包含数字和字符串元素,则根据 BSON 比较顺序。 对字符串元素进行排序,使其在数字元素之前。

创建一个包含以下文档的 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 ]}
])

以下示例使用 $maxN 操作符检索每个玩家的两个最高分。最高分在由 $addFields 创建的新字段 maxScores 中返回。

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

此操作返回以下结果

[{
"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 ]
}]

返回

最大N