정의
구문
표현식 연산자 로 사용되는 경우 $topN 의 구문은 다음과 같습니다.
{ $topN: { n: <expression>, sortBy: <expression>, input: <expression> } }
행동
정렬 동작
MongoDB sortBy 값을 기준으로 input 배열 정렬합니다. 다음 표에는 다양한 정렬 옵션의 예가 나와 있습니다.
input | sortBy | 정렬됨 input | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
| | ||||||||||
|
| | ||||||||||
|
| |
Input Values
input 필드 배열 로 해석되어야 합니다. 배열 아닌 input 을(를) 지정하면 MongoDB 오류가 발생합니다.
예시
movies 다음 예시 sample_mflix 샘플 데이터 세트의 컬렉션 사용합니다. 이 데이터 세트를 배포서버 에 로드하는 방법에 대한 자세한 내용은 샘플 데이터 세트 로드를 참조하세요.
movies 컬렉션 에는 다음 예시 와 유사한 문서가 포함되어 있습니다.
{ _id: ObjectId('573a1396f29313caabce4a9a'), year: 1972, genres: [ 'Crime', 'Drama' ], title: 'The Godfather', cast: [ 'Marlon Brando', 'Al Pacino', 'James Caan', 'Richard S. Castellano' ], directors: [ 'Francis Ford Coppola' ], runtime: 175, ... }
다음 집계 파이프라인 cast 배열 에서 $topN 을(를) 사용합니다.
db.movies.aggregate([ { $match: { title: "The Godfather" } }, { $project: { _id: 0, title: 1, firstThreeCastMembersAlphabetically: { $topN: { n: 3, sortBy: 1, input: "$cast" } } } } ])
[ { title: 'The Godfather', firstThreeCastMembersAlphabetically: [ 'Al Pacino', 'James Caan', 'Marlon Brando' ] } ]
이 예시 에서 $topN 은 기존 cast 배열 알파벳 오름차순으로 정렬하고 처음 세 값을 반환합니다.