文章目录
- 语法
- 使用
- 举例
$minN
聚合运算符返回数组中最小的n个值。
语法
{ $minN: { n: <expression>, input: <expression> } }
参数说明:
n
:正整数表达式,用于指定返回数组元素的数量。input
:可以解析为数组的表达式。
使用
n
不能小于1$minN
忽略数组中的null值- 如果
n
大于等于input
数组元素数量,返回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 ]}
])
下面的聚合操作使用$minN
运算符检索得分最高的两个玩家,并使用$addFields
阶段将得分最高的放到一个新字段maxScores
:
db.scores.aggregate([{ $addFields: { maxScores: { $minN: { 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 ]
}]