Docs 菜单

Docs 主页开发应用程序MongoDB Manual

$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 对文档进行分组。此示例只有一个 gameIdG1

  • PlayerD 分数缺失,且 PlayerEscore 为空。这些值都被视为空值。

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

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

  • PlayerDPlayerE并列为底部元素。 PlayerD作为底部的score返回。

  • 如需对多个空值的情况确定需要采取的打破平局的行为,请在 ``sortBy`` 中添加更多字段。

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

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

$bottom 支持作为 window operator

调用 $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

  • 指定 $bottomoutput : ["$playerId"," $score"] 输出的字段。

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

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

操作返回以下结果:

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

您可以使用$bottom累加器来查找每个游戏中的score底部。

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

示例管道:

  • 使用 $groupgameId 对结果进行分组。

  • 使用$bottom返回每个游戏的最低score

  • 指定 $bottomoutput : ["$playerId", "$score"] 输出的字段。

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

操作返回以下结果:

[
{ _id: 'G2', playerId: [ 'PlayerA', 10 ] },
{ _id: 'G1', playerId: [ 'PlayerD', 1 ] }
]
← $bitXor(聚合)