文档菜单
文档首页
/
MongoDB 手册
/ / /

$bottom (聚合累加器)

本页内容

  • 定义
  • 语法
  • 行为
  • 限制
  • 示例
$bottom

在版本5.2.

根据指定的排序顺序返回组内的底部元素。

{
$bottom:
{
sortBy: { <field1>: <sort order>, <field2>: <sort order> ... },
output: <expression>
}
}
字段
必要性
描述
sortBy
必需
指定结果顺序,语法类似于$sort.
输出
必需
表示组中每个元素的输出,可以是任何表达式。

考虑以下聚合操作,该操作从一组分数中返回底部文档

  • $bottom不会过滤掉空值。

  • $bottom将缺失值转换为空值。

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 }
}
}
}
}
] )

在此示例中

  • $documents创建了包含玩家分数的文档。

  • $groupgameId对文档进行分组。此示例只有一个gameId,即G1

  • PlayerD有一个缺失的分数,而PlayerE有一个空的score。这两个值都被视为空值。

  • 字段 playerIdscore 被指定为 输出 : ["$playerId", " $score"],并以数组值的形式返回。

  • 使用 sortBy: { "score": -1 } 指定排序顺序。

  • PlayerDPlayerE 在最低元素上并列。将 PlayerD 作为最低 score 返回。

  • 为了对多个空值有更确定的平局打破行为,请向 sortBy 添加更多字段。

[
{
_id: 'G1',
playerId: [ 'PlayerD', null ]
}
]

$bottom 不支持作为 聚合表达式。

$bottom 支持作为 窗口操作符

调用 $bottom 的聚合管道受限于 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 }
])

您可以使用 $bottom 累加器在单个游戏中找到最低分数。

db.gamescores.aggregate( [
{
$match : { gameId : "G1" }
},
{
$group:
{
_id: "$gameId",
playerId:
{
$bottom:
{
output: [ "$playerId", "$score" ],
sortBy: { "score": -1 }
}
}
}
}
] )

示例管道

  • 使用 $match 在单个 gameId 上过滤结果。在这种情况下,G1

  • 使用 $groupgameId 分组结果。在这种情况下,G1

  • 使用 output : ["$playerId"," $score"] 指定 $bottom 的输出字段。

  • 使用 sortBy: { "score": -1 } 按降序对分数进行排序。

  • 使用 $bottom 返回游戏的最低分数。

此操作返回以下结果

[ { _id: 'G1', playerId: [ 'PlayerD', 1 ] } ]

您可以使用 $bottom 累加器找到每个游戏的最低 分数

db.gamescores.aggregate( [
{
$group:
{ _id: "$gameId", playerId:
{
$bottom:
{
output: [ "$playerId", "$score" ],
sortBy: { "score": -1 }
}
}
}
}
] )

示例管道

  • 使用 $groupgameId 分组结果。

  • 使用 $bottom 返回每场比赛的底部 得分

  • 使用 output : ["$playerId", "$score"] 指定 $bottom 输出的字段。

  • 使用 sortBy: { "score": -1 } 按降序对分数进行排序。

此操作返回以下结果

[
{ _id: 'G2', playerId: [ 'PlayerA', 10 ] },
{ _id: 'G1', playerId: [ 'PlayerD', 1 ] }
]

返回

$bitXor