Database Manual / Reference / Query Language / Accumulators

$maxN (aggregation accumulator)(聚合累加器)

Definition定义

$maxN

New in version 5.2.在版本5.2中新增。

Returns an aggregation of the maxmimum value n elements within a group. If the group contains fewer than n elements, $maxN returns all elements in the group.返回组内最大值n个元素的聚合。如果组包含的元素少于n个,$maxN将返回组中的所有元素。

Syntax语法

{
$maxN:
{
input: <expression>,
n: <expression>
}
}
  • input specifies an expression that is the input to $maxN. It is evaluated for each element in the group and $maxN preserves the maximum n values.指定一个表达式作为$maxN的输入。对组中的每个元素进行评估,$maxN保留最大n值。
  • n limits the number of results per group and n has to be a positive integral expression that is either a constant or depends on the _id value for $group.n限制了每组的结果数量,n必须是一个正积分表达式,要么是常数,要么取决于$group_id值。

Behavior行为

Result Type结果类型

$maxN compares input data following the BSON Comparison order to determine the appropriate output type. When the input data contains multiple data types, the $maxN output type is the highest in the comparison order.按照BSON比较顺序比较输入数据,以确定适当的输出类型。当输入数据包含多种数据类型时,$maxN输出类型在比较顺序中最高。

Null and Missing Valuesnull值和缺失值

  • $maxN filters out null and missing values.筛选掉null值和缺失值。

Consider the following aggregation that returns the maximum n documents from a group:考虑以下聚合,它从一个组中返回最多n个文档:

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",
maximumThreeScores:
{
$maxN:
{
input: "$score",
n: 4
}
}
}
}
] )

In this example:在这个例子中:

  • $documents creates the literal documents that contain player scores.创建包含玩家分数的文字文档。
  • $group groups the documents by gameId. This example has only one gameId, G1.gameId对文档进行分组。这个例子只有一个gameId G1
  • PlayerD has a missing score and PlayerE has a null score. These values are both considered as null.PlayerD缺少分数,PlayerE的分数为空。这些值都被视为null
  • The maximumThreeScores field is specified as $maxN with input : "$score" and returned as an array.maximumThreeScores字段指定为$maxN配合input : "$score",并以数组形式返回。
  • Since there are only 3 documents with scores maxN returns the maximum 3 score fields even though n = 4.由于只有3个文档具有分数,即使n=4maxN也会返回最多3个scores字段。
[
{
_id: 'G1',
maximumThreeScores: [ 3, 2, 1 ]
}
]

Comparison of $maxN and $topN Accumulators$maxN$topN累加器的比较

Both $maxN and $topN accumulators can accomplish similar results.$maxN$topN累加器都可以实现类似的结果。

In general:一般来说:

  • $maxN has the advantage of finding maximum values in no particular sort order. If you want to know the maximum values for n documents use $maxN.具有在没有特定排序顺序的情况下找到最大值的优点。如果你想知道n个文档的最大值,请使用$maxN
  • If guaranteing a particular sort order is a requirement use $topN.如果需要保证特定的排序顺序,请使用$topN
  • Use $topN if you don't intend on sorting on the output values.如果您不打算对输出值进行排序,请使用$topN

Restrictions限制

Window Function and Aggregation Expression Support窗口函数和聚合表达式支持

You can use $maxN as an accumulator.您可以使用$maxN作为累加器。

$maxN is supported as an aggregation expression.支持作为聚合表达式

$maxN is supported as a window operator.支持作为窗口运算符

Memory Limit Considerations内存限制注意事项

Aggregation pipelines which call $maxN are subject to the 100 MB limit. If this limit is exceeded for an individual group, the aggregation fails with an error.调用$maxN的聚合管道受100MB限制。如果单个组超过此限制,聚合将失败并出现错误。

Examples示例

Consider a gamescores collection with the following documents:考虑一个包含以下文档的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 }
])

Find the Maximum Three Scores for a Single Game找到单场比赛的最高三分

You can use the $maxN accumulator to find the maximum three scores in a single game.您可以使用$maxN累加器来计算单场比赛中的最大三分。

db.gamescores.aggregate( [
{
$match : { gameId : "G1" }
},
{
$group:
{
_id: "$gameId",
maxThreeScores:
{
$maxN:
{
input: ["$score","$playerId"],
n:3
}
}
}
}
] )

The example pipeline:示例管道:

  • Uses $match to filter the results on a single gameId. In this case, G1.使用$match筛选单个gameId的结果。在这种情况下,G1
  • Uses $group to group the results by gameId. In this case, G1.使用$groupgameId对结果进行分组。在这种情况下,G1
  • Specifies the fields that are input for $maxN with input : ["$score","$playerId"].使用input : ["$score","$playerId"]指定$maxN的输入字段。
  • Uses $maxN to return the maximum three score elements for the G1 game with n : 3.使用$maxN配合n:3返回G1游戏的最大三个分数元素。

The operation returns the following results:该操作返回以下结果:

[
{
_id: 'G1',
maxThreeScores: [ [ 99, 'PlayerC' ], [ 33, 'PlayerB' ], [ 31, 'PlayerA' ] ]
}
]

Finding the Maximum Three Scores Across Multiple Games在多个游戏中找到最多三个分数

You can use the $maxN accumulator to find the maximum n scores in each game.您可以使用$maxN累加器来计算每场比赛中的最大n分。

db.gamescores.aggregate( [
{
$group:
{
_id: "$gameId",
maxScores:
{
$maxN:
{
input: ["$score","$playerId"],
n: 3
}
}
}
}
] )

The example pipeline:示例管道:

  • Uses $group to group the results by gameId.使用$groupgameId对结果进行分组。
  • Uses $maxN to return the maximum three score elements for each game with n: 3.使用$maxN配合n:3返回每个游戏的最大三个分数元素。
  • Specifies the fields that are input for $maxN with input: ["$score","$playerId"].使用input: ["$score","$playerId"]指定$maxN的输入字段。

The operation returns the following results:该操作返回以下结果:

[
{
_id: 'G1',
maxScores: [ [ 99, 'PlayerC' ], [ 33, 'PlayerB' ], [ 31, 'PlayerA' ] ]
},
{
_id: 'G2',
maxScores: [ [ 80, 'PlayerD' ], [ 66, 'PlayerC' ], [ 14, 'PlayerB' ] ]
}
]

Computing n Based on the Group Key for $group基于$Group的组键计算n

You can also assign the value of n dynamically. In this example, the $cond expression is used on the gameId field.您还可以动态地分配n的值。在这个例子中,$cond表达式用于gameId字段。

db.gamescores.aggregate([
{
$group:
{
_id: {"gameId": "$gameId"},
gamescores:
{
$maxN:
{
input: ["$score","$playerId"],
n: { $cond: { if: {$eq: ["$gameId","G2"] }, then: 1, else: 3 } }
}
}
}
}
] )

The example pipeline:示例管道:

  • Uses $group to group the results by gameId.使用$groupgameId对结果进行分组。
  • Specifies the fields that input for $maxN with input : ["$score","$playerId"].使用input : ["$score","$playerId"]$maxN指定输入的字段。
  • If the gameId is G2 then n is 1, otherwise n is 3.如果gameIdG2,则n1,否则n3

The operation returns the following results:该操作返回以下结果:

[
{ _id: { gameId: 'G2' }, gamescores: [ [ 80, 'PlayerD' ] ] },
{
_id: { gameId: 'G1' },
gamescores: [ [ 99, 'PlayerC' ], [ 33, 'PlayerB' ], [ 31, 'PlayerA' ] ]
}
]