문서 메뉴
문서 홈
/
MongoDB Shell

애그리게이션 파이프라인 실행

이 페이지의 내용

  • 애그리게이션 구문 이해
  • 예제

MongoDB Shell을 사용하여 컬렉션에서 집계 파이프라인 을 실행할 수 있습니다. 집계 파이프라인은 선택한 파이프라인 단계를 기반으로 문서를 집계된 결과로 변환합니다.

집계가 일반적으로 사용되는 경우는 다음과 같습니다.

  • 주어진 표현식을 기준으로 데이터를 그룹화.

  • 여러 필드를 기반으로 결과를 계산하고 해당 결과를 새 필드에 저장.

  • 데이터를 필터링하여 지정된 기준과 일치하는 하위 집합을 반환.

  • 데이터 정렬.

애그리게이션을 실행하면 MongoDB 셸이 결과를 터미널에 직접 출력합니다.

MongoDB 집계 파이프라인은 여러 단계 로 구성됩니다. 각 단계에서는 문서가 파이프라인을 통과할 때 문서를 변환합니다. 파이프라인 단계는 모든 입력 문서에 대해 하나의 출력 문서를 생성할 필요가 없습니다. 예를 들어, 일부 단계에서는 새 문서를 생성하거나 문서를 필터링할 수 있습니다.

MongoDB 셸에서 다음 구문을 사용하여 애그리게이션 .파이프라인을 생성할 수 있습니다.

1db.<collection>.aggregate([
2 {
3 <$stage1>
4 },
5 {
6 <$stage2>
7 }
8 ...
9])

이 페이지의 예제는 Atlas 샘플 데이터 세트 를 참조합니다. 이 예제에 따라 무료 Atlas 클러스터를 생성하고 해당 클러스터를 샘플 데이터로 채울 수 있습니다. 자세한 내용 은 Atlas 시작하기를 참조하세요.

아래 예제에서는 Atlas sample_mflix 샘플 데이터 세트의 movies 컬렉션을 사용합니다.

movies 컬렉션의 각 문서는 영화를 설명합니다.

1{
2 _id: 573a1397f29313caabce8347,
3 fullplot: 'In a cyberpunk vision of the future, man has developed the technology to create replicants, human clones used to serve in the colonies outside Earth but with fixed lifespans. In Los Angeles, 2019, Deckard is a Blade Runner, a cop who specializes in terminating replicants. Originally in retirement, he is forced to re-enter the force when four replicants escape from an off-world colony to Earth.',
4 imdb: { rating: 8.2, votes: 419589, id: 83658 },
5 year: 1982,
6 plot: 'A blade runner must pursue and try to terminate four replicants who stole a ship in space and have returned to Earth to find their creator.',
7 genres: [ 'Sci-Fi', 'Thriller' ],
8 rated: 'R',
9 metacritic: 88,
10 title: 'Blade Runner',
11 lastupdated: '2015-09-04 00:05:51.990000000',
12 languages: [ 'English', 'German', 'Cantonese', 'Japanese', 'Hungarian' ],
13 writers: [
14 'Hampton Fancher (screenplay)',
15 'David Webb Peoples (screenplay)',
16 'Philip K. Dick (novel)'
17 ],
18 type: 'movie',
19 tomatoes: {
20 viewer: { rating: 4, numReviews: 331213, meter: 91 },
21 dvd: 1997-08-27T00:00:00.000Z,
22 critic: { rating: 8.5, numReviews: 102, meter: 90 },
23 lastUpdated: 2015-09-12T17:48:21.000Z,
24 consensus: "Misunderstood when it first hit theaters, the influence of Ridley Scott's mysterious, neo-noir Blade Runner has deepened with time. A visually remarkable, achingly human sci-fi masterpiece.",
25 rotten: 10,
26 production: 'Warner Bros. Pictures',
27 fresh: 92
28 },
29 poster: 'https://m.media-amazon.com/images/M/MV5BNzQzMzJhZTEtOWM4NS00MTdhLTg0YjgtMjM4MDRkZjUwZDBlXkEyXkFqcGdeQXVyNjU0OTQ0OTY@._V1_SY1000_SX677_AL_.jpg',
30 num_mflix_comments: 1,
31 released: 1982-06-25T00:00:00.000Z,
32 awards: {
33 wins: 13,
34 nominations: 15,
35 text: 'Nominated for 2 Oscars. Another 11 wins & 15 nominations.'
36 },
37 countries: [ 'USA', 'Hong Kong', 'UK' ],
38 cast: [
39 'Harrison Ford',
40 'Rutger Hauer',
41 'Sean Young',
42 'Edward James Olmos'
43 ],
44 directors: [ 'Ridley Scott' ],
45 runtime: 117
46}

이 튜토리얼에서 집계한 문서는 sample_mflix.movies 컬렉션에 위치합니다. 이 컬렉션을 포함하는 데이터베이스로 전환하려면 다음 명령을 사용합니다:

use sample_mflix

다음 파이프라인을 고려합니다.

1db.movies.aggregate([
2
3 // First Stage
4
5 { $project: { _id: 0, genres: 1, imdb: 1, title: 1 } },
6
7 // Second Stage
8
9 { $unwind: "$genres" },
10
11 // Third Stage
12
13 { $group:
14 { _id: "$genres",
15 averageGenreRating: { $avg: "$imdb.rating" }
16 }
17 },
18
19 // Fourth Stage
20
21 { $sort: { averageGenreRating: -1 } }
22] )

이 파이프라인은 4단계로 애그리게이션을 수행합니다:

첫 번째 단계

$project 단계에서는 다음 필드가 포함된 문서를 다음 파이프라인 단계로 전달합니다.

  • genres

  • imdb

  • title

이러한 필드를 모두 포함하지 않는 collection의 문서는 다음 파이프라인 단계로 전달되지 않습니다.

참고

$project 단계는 다음 단계로 전달하는 문서에서 _id 필드를 표시하지 않기 위해 _id: 0를 지정합니다.

자세한 내용은 MongoDB 매뉴얼을 참조하세요.

$project 단계는 예시 문서를 변환하고 아래 출력을 다음 파이프라인 단계에 전달합니다.

1{
2 imdb: { rating: 8.2, votes: 419589, id: 83658 },
3 genres: [ 'Sci-Fi', 'Thriller' ],
4 title: 'Blade Runner'
5}
두 번째 단계

$unwind 단계는 genres 배열의 각 요소에 대한 문서를 다음 파이프라인 단계로 전달합니다.

$unwind 단계는 원본 예시 문서에서 다음 두 문서를 생성한 후 다음 파이프라인 단계로 전달합니다.

1{
2 imdb: { rating: 8.2, votes: 419589, id: 83658 },
3 genres: 'Sci-Fi',
4 title: 'Blade Runner'
5}
1{
2 imdb: { rating: 8.2, votes: 419589, id: 83658 },
3 genres: 'Thriller',
4 title: 'Blade Runner'
5}
세 번째 단계

$group 단계:

  • 이전 파이프라인 단계에서 받은 문서에서 고유한 장르 값을 조회합니다.

  • _id가 장르 이름인 각 고유 장르에 대한 문서를 생성합니다.

  • 장르와 일치하는 모든 문서의 평균 imdb.rating을 포함하는 각 새 문서에 필드 averageGenreRating을 추가합니다.

  • 새 문서를 다음 파이프라인 단계로 전달합니다.

이 단계에서는 다음 내용과 유사한 문서를 다음 파이프라인 단계로 보냅니다.

1{ _id: 'Sport', averageGenreRating: 6.781233933161954 },
2{ _id: 'History', averageGenreRating: 7.202306920762287 },
3{ _id: 'Biography', averageGenreRating: 7.097142857142857 },
4{ _id: 'Adventure', averageGenreRating: 6.527788649706458 },
5{ _id: 'Family', averageGenreRating: 6.36096256684492 },
6{ _id: 'Crime', averageGenreRating: 6.730478683620045 },
7{ _id: 'Western', averageGenreRating: 6.879197080291971 },
8{ _id: 'Fantasy', averageGenreRating: 6.42495652173913 },
9{ _id: 'Talk-Show', averageGenreRating: 7 },
10{ _id: 'Documentary', averageGenreRating: 7.365266635205286 },
11{ _id: 'War', averageGenreRating: 7.183944374209861 },
12{ _id: 'Short', averageGenreRating: 7.355813953488372 },
13{ _id: 'Horror', averageGenreRating: 5.84110718492344 },
14{ _id: 'Film-Noir', averageGenreRating: 7.503809523809523 },
15{ _id: 'News', averageGenreRating: 7.254901960784314 },
16{ _id: 'Thriller', averageGenreRating: 6.322121555303888 },
17{ _id: 'Action', averageGenreRating: 6.3774842271293375 },
18{ _id: 'Music', averageGenreRating: 6.923452380952381 },
19{ _id: 'Animation', averageGenreRating: 6.917993795243019 },
20{ _id: 'Drama', averageGenreRating: 6.830528688822631 }
4단계
$sort 단계는 averageGenreRating 필드 값을 기준으로 이전 단계에서 수신한 문서를 내림차순으로 정렬합니다.

예제 파이프라인 을 실행하면 MongoDB Shell은 다음과 유사한 문서를 터미널에 출력합니다.

1[
2 { _id: 'Film-Noir', averageGenreRating: 7.503809523809523 },
3 { _id: 'Documentary', averageGenreRating: 7.365266635205286 },
4 { _id: 'Short', averageGenreRating: 7.355813953488372 },
5 { _id: 'News', averageGenreRating: 7.254901960784314 },
6 { _id: 'History', averageGenreRating: 7.202306920762287 },
7 { _id: 'War', averageGenreRating: 7.183944374209861 },
8 { _id: 'Biography', averageGenreRating: 7.097142857142857 },
9 { _id: 'Talk-Show', averageGenreRating: 7 },
10 { _id: 'Music', averageGenreRating: 6.923452380952381 },
11 { _id: 'Animation', averageGenreRating: 6.917993795243019 },
12 { _id: 'Western', averageGenreRating: 6.879197080291971 },
13 { _id: 'Drama', averageGenreRating: 6.830528688822631 },
14 { _id: 'Sport', averageGenreRating: 6.781233933161954 },
15 { _id: 'Crime', averageGenreRating: 6.730478683620045 },
16 { _id: 'Musical', averageGenreRating: 6.696913580246913 },
17 { _id: 'Romance', averageGenreRating: 6.695711554220159 },
18 { _id: 'Mystery', averageGenreRating: 6.563317384370015 },
19 { _id: 'Adventure', averageGenreRating: 6.527788649706458 },
20 { _id: 'Comedy', averageGenreRating: 6.479626461362988 },
21 { _id: 'Fantasy', averageGenreRating: 6.42495652173913 }
22]

다음도 참조하세요.

← 문서 삭제