MongoDB聚合运算符:$topN
$topN
聚合运算符返回分组中指定顺序的最前面
n
个元素,如果分组中的元素数量小于
n
,则返回分组的全部元素。从MongoDB5.2开始支持。
语法
{
$topN:
{
n: <expression>,
sortBy: {
<field1>: <sort order>, <field2>: <sort order> ... },
output: <expression>
}
}
n
用于限制每组结果的数量,必须是正整数表达式,要么是常数,要么取决于$group
的_id
值sortBy
制定返回结果的顺序,语法类似于$sort
output
指定分组元素输出的内容,可以是任何合法的表达式。
用法
$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
都是G1
PlayerD