AI エージェント向け: ドキュメントインデックスは https://www.mongodb.com/ja-jp/docs/llms.txt で利用できます。すべてのページの markdown バージョンは、いずれかの URL パスに .md を追加することで利用できます。
Docs Menu

$maxN(演算子)

$maxN

バージョン5.2の新機能。

配列内の n つの最大値を返します。

$maxN の構文は次のとおりです。

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

n

An expression that resolves to a positive integer. The integer specifies the number of array elements that $maxN returns.

input

最大 個のn要素を返す配列に解決される

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

  • $maxN filters out null values found in the input array.

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

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

The following example uses the $maxN operator to retrieve the two highest scores for each player. The highest scores are returned in the new field maxScores created by $addFields.

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 ]
}]
このページを評価