정의
구문
$maxN 의 구문은 다음과 같습니다:
{ $maxN: { n: <expression>, input: <expression> } }
필드 | 설명 |
|---|---|
| An expression that resolves to a positive integer. The integer specifies the number of array elements that |
| 최대 |
행동
1보다 작은n값은 지정할 수 없습니다.$maxNfilters outnullvalues found in theinputarray.If the specified
nis greater than or equal to the number of elements in theinputarray,$maxNreturns all elements in theinputarray.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 ] }]