MongoDB聚合运算符:$topN
$topN聚合运算符返回分组中指定顺序的最前面
n个元素,如果分组中的元素数量小于
n,则返回分组的全部元素。从MongoDB5.2开始支持。
语法
{
$topN:
{
n: <expression>,
sortBy: {
<field1>: <sort order>, <field2>: <sort order> ... },
output: <expression>
}
}
n用于限制每组结果的数量,必须是正整数表达式,要么是常数,要么取决于$group的_id值sortBy制定返回结果的顺序,语法类似于$sortoutput指定分组元素输出的内容,可以是任何合法的表达式。
用法
$topN不支持作为聚合表达式。$topN只支持作为window 操作符。- 聚合管道调用
$topN受100M的限制,如果单组超过这一限制将报错。
关于null和缺失值的处理
$topN不会过滤掉空值$topN会将缺失值转换为null
db.aggregate( [
{
$documents: [
{
playerId: "PlayerA", gameId: "G1", score: 1 },
{
playerId: "PlayerB", gameId: "G1", score: 2 },
{
playerId: "PlayerC", gameId: "G1", score: 3 },
{
playerId: "PlayerD", gameId: "G1"},
{
playerId: "PlayerE", gameId: "G1", score: null }
]
},
{
$group:
{
_id: "$gameId",
playerId:
{
$topN:
{
output: [ "$playerId", "$score" ],
sortBy: {
"score": 1 },
n: 3
}
}
}
}
] )
在这个例子中:
- 使用
$documents阶段创建了一些字面量(常量)文档,包含了选手的得分 $group阶段根据gameId对文档进行了分组,显然文档中的gameId都是G1PlayerD的得分缺失,PlayerE的得分为null,他们的得分都会被当

最低0.47元/天 解锁文章
1354

被折叠的 条评论
为什么被折叠?



