$top (聚合累加器)
定义
语法
{ $top: { sortBy: { <field1>: <sort order>, <field2>: <sort order> ... }, output: <expression> } }
字段 | 必要性 | 描述 |
---|---|---|
sortBy | 必需 | 指定结果顺序,语法类似于 $sort . |
输出 | 必需 | 代表组内每个元素的输出,可以是任何表达式。 |
行为
空值和缺失值
考虑以下聚合操作,该操作返回一组分数中的顶级文档
$top
不会过滤掉空值。$top
将缺失值转换为空值。
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: { $top: { output: [ "$playerId", "$score" ], sortBy: { "score": 1 } } } } } ] )
在此示例中
$documents
创建包含玩家得分的字面文档。$group
按照文档的gameId
对文档进行分组。此示例只有一个gameId
,即G1
。PlayerD
缺失分数,而PlayerE
的score
为空。这两个值都被视为空。将
playerId
和score
字段指定为output : ["$playerId"," $score"]
,并以数组值返回。使用
sortBy: { "score": 1 }
指定排序顺序。PlayerD
和PlayerE
在最高元素中并列。返回最高score
时,返回PlayerD
。为了对多个空值有更确定的分解行为,请向
sortBy
添加更多字段。
[ { _id: 'G1', playerId: [ 'PlayerD', null ] } ]
限制
窗口函数和聚合表达式支持
$top
不是一个聚合表达式。
$top
是一个窗口操作符
。
内存限制考虑
调用 $top
的聚合管道受限于 100 MB。如果单个分组的限制被超过,聚合将因错误而失败。
示例
考虑一个包含以下文档的 gamescores
集合
db.gamescores.insertMany([ { playerId: "PlayerA", gameId: "G1", score: 31 }, { playerId: "PlayerB", gameId: "G1", score: 33 }, { playerId: "PlayerC", gameId: "G1", score: 99 }, { playerId: "PlayerD", gameId: "G1", score: 1 }, { playerId: "PlayerA", gameId: "G2", score: 10 }, { playerId: "PlayerB", gameId: "G2", score: 14 }, { playerId: "PlayerC", gameId: "G2", score: 66 }, { playerId: "PlayerD", gameId: "G2", score: 80 } ])
查找最高 得分
您可以使用 $top
累加器在单场比赛中查找最高得分。
db.gamescores.aggregate( [ { $match : { gameId : "G1" } }, { $group: { _id: "$gameId", playerId: { $top: { output: [ "$playerId", "$score" ], sortBy: { "score": -1 } } } } } ] )
示例管道
使用
$match
在单个gameId
上过滤结果。在本例中,为G1
。使用
$group
按照游戏ID分组结果。在本例中,为G1
。使用
output : ["$playerId"," $score"]
指定 $top 输出的字段。使用
sortBy: { "score": -1 }
按降序对得分进行排序。使用
$top
返回游戏中的最高得分。
此操作返回以下结果
[ { _id: 'G1', playerId: [ 'PlayerC', 99 ] } ]
在多场比赛中查找最高 得分
您可以使用 $top
累加器查找每场比赛的最高 得分
。
db.gamescores.aggregate( [ { $group: { _id: "$gameId", playerId: { $top: { output: [ "$playerId", "$score" ], sortBy: { "score": -1 } } } } } ] )
示例管道
使用
$group
按游戏ID分组结果。使用
$top
返回每场比赛的最高得分
。指定使用
output : ["$playerId", "$score"]
输出的字段,用于$top
。使用
sortBy: { "score": -1 }
按降序对得分进行排序。
此操作返回以下结果
[ { _id: 'G2', playerId: [ 'PlayerD', 80 ] }, { _id: 'G1', playerId: [ 'PlayerC', 99 ] } ]