このバージョンのドキュメントはアーカイブされており、サポートされなくなりました。6.0 配置をアップグレードするには、 MongoDB 7.0 のアップグレード手順 を参照してください。
定義
Tip
構文
$maxN の構文は次のとおりです。
{ $maxN: { n: <expression>, input: <expression> } }
動作
1nの値は指定できません。$maxNは、input配列にあるnull値をフィルタリングします。指定された
nがinput配列内の要素数以上の場合、$maxNはinput配列内のすべての要素を返します。inputが配列以外の値に解決される場合、集計操作はエラーになります。inputに数値要素と string 要素の両方が含まれている場合、string 要素はBSON 比較順序に従って数値要素の前にソートされます。
例
次のドキュメントを使用して scores コレクションを作成します。
db.scores.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, "2", 3489, 9 ]} ])
次の例では、 $maxN演算子を使用して、各プレイヤーの最高のスコアを 2 つ検索します。 最高スコアは、 $addFieldsによって作成された新しいフィールドmaxScoresに返されます。
db.scores.aggregate([ { $addFields: { maxScores: { $maxN: { n: 2, input: "$score" } } } } ])
この操作は次の結果を返します。
[{ "playerId": 1, "score": [ 1, 2, 3 ], "maxScores": [ 3, 2 ] }, { "playerId": 2, "score": [ 12, 90, 7, 89, 8 ], "maxScores": [ 90, 89 ] }, { "playerId": 3, "score": [ null ], "maxScores": [ ] }, { "playerId": 4, "score": [ ], "maxScores": [ ] }, { "playerId": 5, "score": [ 1293, "2", 3489, 9 ], "maxScores": [ "2", 3489 ] }]