Docs Menu

$firstN

バージョン 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.

$firstN

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.

When used as an aggregation accumulator, $firstN has the following 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.

  • $firstNは null 値を除外しません。

  • $firstNは欠落値を 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
}
}
}
}
] )

この例では、次のことが行われます。

  • $documentsは、プレイヤーのスコアを含むリテラル ドキュメントを作成します。

  • $groupはドキュメントをgameIdでグループ化します。 この例ではgameIdG1は 1 つのみです。

  • PlayerDにはスコアがあり、 PlayerEには null scoreがあります。 これらの値は両方とも 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 ]
}
]

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

一般に、

  • 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.

$firstN is supported as an aggregation expression.

$firstNwindow operatorとしてサポートされています。

以下のドキュメントを持つ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 }
])

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
}
}
}
}
] )

サンプル パイプライン:

  • $matchを使用して結果を単一のgameIdでフィルタリングします。 この場合は、 G1ます。

  • $groupを使用して結果をgameIdでグループ化します。 この場合は、 G1ます。

  • を使用して$firstN input : ["$playerId"," $score"]に入力するフィールドを指定します。

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

この操作は次の結果を返します。

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

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
}
}
}
}
] )

サンプル パイプライン:

  • $groupを使用して結果をgameIdでグループ化します。

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

  • を使用して$firstN input : ["$playerId", "$score"]に入力するフィールドを指定します。

この操作は次の結果を返します。

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

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

この例では、次のことが行われます。

  • {$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
}
}
}
}
] )

この操作は次の結果を返します。

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

また、 nの値を動的に割り当てることもできます。 この例では、 $cond式はgameIdフィールドで使用されています。

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

サンプル パイプライン:

  • $groupを使用して結果をgameIdでグループ化します。

  • input : "$score"を使用して$firstNに入力するフィールドを指定します。

  • gameIdG2の場合、 nは 1、それ以外の場合、 nは 3 になります。

この操作は次の結果を返します。

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

You can also use $firstN as an aggregation expression.

この例では、次のことが行われます。

  • $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
}
}
}
}
] )

この操作は次の結果を返します。

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

When used as an array operator, $firstN has the following syntax:

{ $firstN: { n: <expression>, input: <expression> } }
フィールド
説明

n

正の整数に解決される式。$firstN整数は、 が返す配列要素の数を指定します。

input

An that resolves to the array from which to return n elements.

  • $firstN returns elements in the same order they appear in the input array.

  • $firstN does not filter out null values in the input array.

  • 1 nの値は指定できません。

  • If the specified n is greater than or equal to the number of elements in the input array, $firstN returns the input array.

  • If input resolves to a non-array value, the aggregation operation errors.

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, NumberLong("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" } } } }
])

この操作は次の結果を返します。

[{
"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, NumberLong("2090845886852"), 23 ],
"firstScores": [ "12.1", 2, NumberLong("2090845886852") ]
}]

以下も参照してください。