Docs HomeMongoDB Manual

$firstN (aggregation accumulator)

Definition

$firstN

New in version 5.2.

Returns an aggregation of the first n elements within a group. The elements returned are meaningful only if in a specified sort order. If the group contains fewer than n elements, $firstN returns all elements in the group.

Syntax

{
   $firstN:
      {
         input: <expression>,
         n: <expression>
      }
}
  • input specifies the field(s) from the document to take the first n of. Input can be any expression.

  • n has to be a positive integral expression that is either a constant or depends on the _id value for $group. For details see group key example.

Behavior

Null and Missing Values

  • $firstN does not filter out null values.

  • $firstN converts missing values to null.

Consider the following aggregation that returns the first five documents from a group:

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",
         firstFiveScores:
            {
               $firstN:
                  {
                     input: "$score",
                     n: 5
                  }
            }
      }
   }
] )

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.

  • PlayerD has a missing score and PlayerE has a null score. These values are both considered as null.

  • The firstFiveScores field is specified using input : "$score" and returned as an array.

  • Since there is no sort criteria the first 5 score fields are returned.

[
   {
      _id: 'G1',
      firstFiveScores: [ 1, 2, 3, null, null ]
   }
]

Comparison of $firstN and $topN Accumulators

Both $firstN and $topN accumulators can accomplish similar results.

In general:

  • If the documents coming into $group are already ordered, you should use $firstN.

  • If you're sorting and selecting the top n elements then you can use $topN to accomplish both tasks with one accumulator.

  • $firstN can be used as an aggregation expression, $topN cannot.

Restrictions

Window Function and Aggregation Expression Support

$firstN is supported as an aggregation expression.

For details on aggregation expression usage see Using $firstN as an Aggregation Expression.

$firstN is supported as a window operator.

Memory Limit Considerations

Aggregation pipelines which call $firstN are subject to the 100 MB limit. If this limit is exceeded for an individual group, the aggregation fails with an error.

Examples

Consider a gamescores collection with the following documents:

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 First Three Player Scores for a Single Game

You can use the $firstN accumulator to find the first three scores in a single game.

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

The example pipeline:

  • Uses $match to filter the results on a single gameId. In this case, G1.

  • Uses $group to group the results by gameId. In this case, G1.

  • Specifies the fields that are input for $firstN with input : ["$playerId"," $score"].

  • Uses $firstN to return the first three documents for the G1 game with n : 3.

The operation returns the following results:

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

Finding the First Three Player Scores Across Multiple Games

You can use the $firstN accumulator to find the first n input fields in each game.

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

The example pipeline:

  • Uses $group to group the results by gameId.

  • Uses $firstN to return the first three documents for each game with n: 3.

  • Specifies the fields that are input for $firstN with input : ["$playerId", "$score"].

The operation returns the following results:

[
   {
      _id: 'G1',
      playerId: [ [ 'PlayerA', 31 ], [ 'PlayerB', 33 ], [ 'PlayerC', 99 ] ]
   },
   {
      _id: 'G2',
      playerId: [ [ 'PlayerA', 10 ], [ 'PlayerB', 14 ], [ 'PlayerC', 66 ] ]
   }
]

Using $sort With $firstN

Using a $sort stage earlier in the pipeline can influence the results of the $firstN accumulator.

In this example:

  • {$sort : { score : -1 } } sorts the highest scores to the back of each group.

  • firstN returns the three highest scores from front of each group.

db.gamescores.aggregate( [
      { $sort : { score : -1 } },
      {
$group: { _id: "$gameId", playerId: { $firstN: { input: [ "$playerId","$score" ], n: 3 } } } } ] )

The operation returns the following results:

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

Computing n Based on the Group Key for $group

You can also assign the value of n dynamically. In this example, the $cond expression is used on the gameId field.

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

The example pipeline:

  • Uses $group to group the results by gameId.

  • Specifies the fields that input for $firstN with input : "$score".

  • If the gameId is G2 then n is 1, otherwise n is 3.

The operation returns the following results:

[
   { _id: { gameId: 'G1' }, gamescores: [ 31, 33, 99 ] },
   { _id: { gameId: 'G2' }, gamescores: [ 10 ] }
]

Using $firstN as an Aggregation Expression

You can also use $firstN as an aggregation expression.

In this example:

  • $documents creates the literal document that contains an array of values.

  • $project is used to return the output of $firstN.

  • _id is omited from the output with _id : 0.

  • $firstN uses the input array of [10, 20, 30, 40].

  • The first three elements of the array are returned for the input document.

db.aggregate( [
   {
      $documents: [
         { array: [10, 20, 30, 40] } ]
   },
   { $project: {
      firstThreeElements:{
                           $firstN:
                           {
                              input: "$array",
                              n: 3
                           }
                        }
               }
   }
] )

The operation returns the following results:

[
   { firstThreeElements: [ 10, 20, 30 ] }
]