Definition
New in version 5.2.
$firstN can be used as an aggregation accumulator or array operator. As
an aggregation accumulator, it returns an aggregation of the first n
elements within a group. As an array operator, it returns the
specified number of elements from the beginning of an array.
Aggregation Accumulator
When $firstN is used as an aggregation accumulator, the elements returned
are meaningful only if they are in a specified sort order. If the group contains
fewer than n elements, $firstN returns all elements in the group.
Syntax
When used as an aggregation accumulator, $firstN has the following syntax:
{ $firstN: { input: <expression>, n: <expression> } }
inputspecifies the field(s) from the document to take the firstnof. Input can be any expression.nhas to be a positive integral expression that is either a constant or depends on the_idvalue for$group. For details see group key example.
Behavior
Null and Missing Values
$firstNdoes not filter out null values.$firstNconverts 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:
$documentscreates the literal documents that contain player scores.$groupgroups the documents bygameId. This example has only onegameId,G1.PlayerDhas a missing score andPlayerEhas a nullscore. These values are both considered as null.The
firstFiveScoresfield is specified usinginput : "$score"and returned as an array.Since there is no sort criteria the first 5
scorefields 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
$groupare already ordered, you should use$firstN.If you're sorting and selecting the top
nelements then you can use$topNto accomplish both tasks with one accumulator.$firstNcan be used as an aggregation expression,$topNcannot.
Restrictions
Window Function and Aggregation Expression Support
$firstN is supported as an
aggregation expression.
$firstN is supported as a
window operator.
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
$matchto filter the results on a singlegameId. In this case,G1.Uses
$groupto group the results bygameId. In this case,G1.Specifies the fields that are input for
$firstNwithinput : ["$playerId"," $score"].Uses
$firstNto return the first three documents for theG1game withn : 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
$groupto group the results bygameId.Uses
$firstNto return the first three documents for each game withn: 3.Specifies the fields that are input for
$firstNwithinput : ["$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.firstNreturns 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
$groupto group the results bygameId.Specifies the fields that input for
$firstNwithinput : "$score".If the
gameIdisG2thennis 1, otherwisenis 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:
$documentscreates the literal document that contains an array of values.$projectis used to return the output of$firstN._idis omited from the output with_id : 0.$firstNuses 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 ] } ]
Array Operator
Syntax
When used as an array operator, $firstN has the following syntax:
{ $firstN: { n: <expression>, input: <expression> } }
Field | Description |
|---|---|
| An expression that resolves to a
positive integer. The integer specifies the number of array elements
that |
| An expression that resolves to the
array from which to return |
Behavior
$firstNreturns elements in the same order they appear in the input array.$firstNdoes not filter outnullvalues in the input array.You cannot specify a value of
nless than1.If the specified
nis greater than or equal to the number of elements in theinputarray,$firstNreturns theinputarray.If
inputresolves to a non-array value, the aggregation operation errors.
Example
The collection games has the following documents:
db.games.insertMany([ { "playerId" : 1, "score" : [ 1, 2, 3 ] }, { "playerId" : 2, "score" : [ 12, 90, 7, 89, 8 ] }, { "playerId" : 3, "score" : [ null ] }, { "playerId" : 4, "score" : [ ] }, { "playerId" : 5, "score" : [ 1293, null, 3489, 9 ]}, { "playerId" : 6, "score" : [ "12.1", 2, Long("2090845886852"), 23 ]} ])
The following example uses the $firstN operator to retrieve the
first three scores for each player. The scores are returned in the new field
firstScores created by $addFields.
db.games.aggregate([ { $addFields: { firstScores: { $firstN: { n: 3, input: "$score" } } } } ])
The operation returns the following results:
[{ "playerId": 1, "score": [ 1, 2, 3 ], "firstScores": [ 1, 2, 3 ] }, { "playerId": 2, "score": [ 12, 90, 7, 89, 8 ], "firstScores": [ 12, 90, 7 ] }, { "playerId": 3, "score": [ null ], "firstScores": [ null ] }, { "playerId": 4, "score": [ ], "firstScores": [ ] }, { "playerId": 5, "score": [ 1293, null, 3489, 9 ], "firstScores": [ 1293, null, 3489 ] }, { "playerId": 6, "score": [ "12.1", 2, Long("2090845886852"), 23 ], "firstScores": [ "12.1", 2, Long("2090845886852") ] }]