“文档” 菜单
文档首页
/
MongoDB Manual
/ / /

$maxN(数组运算符)

在此页面上

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

5.2 版本中的新增功能

返回数组中 n 个最大值。

提示

另请参阅:

$minN

$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 ]
}]
← $maxN(聚合累加器)