定义
根据指定的排序顺序返回组内的底部元素。
可在以下阶段使用:
注意
消歧
本页介绍了 $bottom 用作 累加器 时的情况。累加器返回对一组输入文档计算的单一聚合值。
您还可以在这些其他上下文中使用 $bottom:
$bottom (expression operator), 它会按指定的排序顺序返回数组中的最后一个元素。$bottom (window function),用于在$setWindowFields阶段中从特定窗口的文档返回底部元素。
语法
{ $bottom: { sortBy: { <field1>: <sort order>, <field2>: <sort order> ... }, output: <expression> }}字段 | 必要性 | 说明 |
|---|---|---|
sortBy | 必需 | 定义每个组中元素的排序顺序,语法类似于 |
输出 | 必需 | 表示组中每个元素的输出,可以是任何表达式。 |
行为
Null 和缺失值
$bottom 不过滤掉空值,并且 $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 } } } } }] )示例管道:
在多年中查找最低评分
你可以使用 $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 } }] )示例管道: