定义
根据指定的排序顺序返回组内的底部元素。
可在以下阶段使用:
注意
消歧
本页描述了用作累加器时的 $bottom。累加器返回一群组输入文档的单个聚合值。
您还可以在 $setWindowFields 阶段使用 $bottom (window function) 返回特定窗口中文档的底部元素。
语法
{ $bottom: { sortBy: { <field1>: <sort order>, <field2>: <sort order> ... }, output: <expression> } }
字段 | 必要性 | 说明 |
|---|---|---|
sortBy | 必需 | 定义每个群组内元素的排名顺序,语法类似于 |
输出 | 必需 | 表示组中每个元素的输出,可以是任何表达式。 |
行为
Null 和缺失值
$bottom 不会过滤掉 null 值,$bottom 会将缺失值转换为 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: { $bottom: { output: [ "$playerId", "$score" ], sortBy: { "score": -1 } } } } } ] )
[ { _id: 'G1', playerId: [ 'PlayerD', null ] } ]
在本例中:
$documents创建包含玩家分数的字面文档。$group按gameId对文档进行分组。此示例只有一个gameId、G1。PlayerD分数缺失,且PlayerE的score为空。这些值都被视为空值。playerId和score字段指定为output : ["$playerId"," $score"],并以数组值形式返回。用
sortBy: { "score": -1 }指定排名顺序。PlayerD和PlayerE并列为底部元素。PlayerD作为底部的score返回。
限制
内存限制注意事项
调用 $bottom 的聚合管道受 100 MB 限制。如果单个群组超过此限制,则聚合失败,并显示错误。
示例
本页上的示例使用 sample_mflix 数据集中的数据。有关如何将此数据集加载到自管理MongoDB 部署中的详细信息,请参阅加载样本数据集。如果对示例数据库进行了任何修改,则可能需要删除并重新创建数据库才能运行本页上的示例。
查找某一类型中的最低评分
您可以使用 $bottom累加器查找单个类型中评分最低的电影。
db.movies.aggregate( [ { $match : { genres: "Comedy" } }, { $group: { _id: "Comedy", lowestRatedMovie: { $bottom: { output: [ "$title", "$imdb.rating" ], sortBy: { "imdb.rating": -1 } } } } } ] )
示例管道:
使用
$match过滤单个类型的结果。在本例中为Comedy。使用
$group将所有喜剧电影群组在单个"Comedy"群组键下。指定
$bottom和output : ["$title", "$imdb.rating"]输出的字段。使用
sortBy: { "imdb.rating": -1 }将群组中的底部元素定义为评级最低的元素。使用
$bottom返回该类型中评分最低的电影。
查找多年以来的最低评级
您可以使用 $bottom累加器查找每年收视率最低的电影。
db.movies.aggregate( [ { $match: { "imdb.rating": { $exists: true }, year: { $gte: 2010, $lte: 2012 } } }, { $group: { _id: "$year", lowestRatedMovie: { $bottom: { output: [ "$title", "$imdb.rating" ], sortBy: { "imdb.rating": -1 } } } } }, { $sort: { _id: 1 } } ] )
示例管道:
使用
$match过滤具有 IMDb 评级的 2010-2012 范围的电影。使用
$group按year对结果分组。使用
$bottom返回每年评分最低的电影。指定
$bottom和output : ["$title", "$imdb.rating"]输出的字段。使用
sortBy: { "imdb.rating": -1 }将群组中的底部元素定义为评级最低的元素。使用
$sort按年份升序对结果进行排序。