$minN (aggregation accumulator)

On this page本页内容

Definition定义

$minN

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

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

Syntax语法

{
   $minN:
      {
         input: <expression>,
         n: <expression>
      }
}
  • input specifies an expression that is the input to $minN. 指定作为$minN输入的表达式。It is evaluated for each element in the group and $minN preserves the minimum n values.它针对组中的每个元素进行求值,$minN保留最小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必须是一个正整数表达式,它要么是常数,要么取决于$group_id值。

Behavior行为

Null and Missing ValuesNull和缺少值

  • $minN filters out null and missing values.筛选出空值和缺少的值。

Consider the following aggregation that returns the minimum 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",
         minimumThreeScores:
            {
               $minN:
                  {
                     input: "$score",
                     n: 4
                  }
            }
      }
   }
] )

In this example:在此示例中:

  • $documents creates the literal documents that contain player scores.创建包含玩家分数的文字文档。
  • $group groups the documents by gameId. gameId对文档进行分组。This example has only one gameId, G1.这个例子只有一个gameIdG1
  • PlayerD has a missing score and PlayerE has a null score. 缺少score,而PlayerEscore为空。These values are both ignored.这些值均被忽略。
  • The minimumThreeScores field is specified as $minN with input : "$score" and returned as an array.minimumThreeScores字段使用input : "$score"指定为$minN,并作为数组返回。
  • Since there are only 3 documents with scores minN returns the minimum 3 score fields even though n = 4.由于只有3个文档带有scores,因此即使n=4,minN也会返回最少3个score字段。
[
   {
   _id: 'G1',
   minimumThreeScores: [ 1, 2, 3 ]
   }
]

Comparison of $minN and $bottomN Accumulators$minN$bottomN累加器的比较

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

In general:

  • $minN has the advantage of finding minimum values in no particular sort order. 具有不按特定排序顺序查找最小值的优点。If you want to know the minimum values for n documents use $minN.如果要知道n个文档的最小值,请使用$minN
  • If guaranteing a particular sort order is a requirement use $bottomN.如果需要保证特定的排序顺序,请使用$bottomN
  • Use $bottomN if you don't intend on sorting on the output values.如果不打算对输出值进行排序,请使用$bottomN

Restrictions限制

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

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

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

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

Memory Limit Considerations内存限制注意事项

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

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 Minimum Three Scores for a Single Game找出一场比赛的最低三分

You can use the $minN accumulator to find the minimum three scores in a single game.您可以使用$minN累加器来查找单个游戏中的最低三分。

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

The example pipeline:示例管道:

  • Uses $match to filter the results on a single gameId. 使用$match筛选单个gameId上的结果。In this case, G1.在本例中为G1
  • Uses $group to group the results by gameId. 使用$groupgameId对结果进行分组。In this case, G1.在本例中为G1
  • Specifies the fields that are input for $minN with input : ["$score","$playerId"].使input : ["$score","$playerId"]指定$minN的输入字段。
  • Uses $minN to return the first three score elements for the G1 game with n : 3.使用$minN返回n:3G1游戏的前三个分数元素。

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

[
   {
      _id: 'G1',
      minScores: [ [ 1, 'PlayerD' ], [ 31, 'PlayerA' ], [ 33, 'PlayerB' ] ]
   }
]

Finding the Minimum Three Documents Across Multiple Games在多个游戏中查找最少三个文档

You can use the $minN accumulator to find the minimum n scores in each game.您可以使用$minN累加器来查找每个游戏中的最小n分。

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

The example pipeline:示例管道:

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

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

[
   {
      _id: 'G2',
      minScores: [ [ 10, 'PlayerA' ], [ 14, 'PlayerB' ], [ 66, 'PlayerC' ] ]
   },
   {
      _id: 'G1',
      minScores: [ [ 1, 'PlayerD' ], [ 31, 'PlayerA' ], [ 33, 'PlayerB' ] ]
   }
]

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

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

db.gamescores.aggregate([
   {
      $group:
      {
         _id: {"gameId": "$gameId"},
         gamescores:
            {
               $minN:
                  {
                     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 $minN with input : ["$score","$playerId"].使用input : ["$score","$playerId"]$minN指定输入的字段。
  • If the gameId is G2 then n is 1, otherwise n is 3.如果gameIdG2,则n为1,否则n为3。

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

[
   { _id: { gameId: 'G2' }, gamescores: [ [ 10, 'PlayerA' ] ] },
   {
      _id: { gameId: 'G1' },
      gamescores: [ [ 1, 'PlayerD' ], [ 31, 'PlayerA' ], [ 33, 'PlayerB' ] ]
   }
]
←  $min (aggregation)$minN (array operator) →