정의
버전 5.0의 신규 항목입니다.
collection에 있는 특정 범위의 문서(창이라고 함) 에 대해 작업을 수행하고 선택한 창 창 연산자를 기반으로 결과를 반환합니다.
예를 들어, $setWindowFields 단계를 사용해 다음을 출력할 수 있습니다.
컬렉션에 있는 두 문서 간의 판매량 차이입니다.
판매 순위.
누적 판매 총액입니다.
데이터를 외부 데이터베이스로 내보내지 않고도 복잡한 시계열 정보를 분석합니다.
구문
$setWindowFields 단계 구문:
{ $setWindowFields: { partitionBy: <expression>, sortBy: { <sort field 1>: <sort order>, <sort field 2>: <sort order>, ..., <sort field n>: <sort order> }, output: { <output field 1>: { <window operator>: <window operator parameters>, window: { documents: [ <lower boundary>, <upper boundary> ], range: [ <lower boundary>, <upper boundary> ], unit: <time unit> } }, <output field 2>: { ... }, ... <output field n>: { ... } } }}$setWindowFields 단계는 다음 필드가 포함된 문서를 사용합니다.
필드 | 필요성 | 설명 |
|---|---|---|
옵션 | 문서를 그룹화하는 표현식을 지정합니다. | |
일부 연산자에 대해 필수(제한 사항 참조) | 파티션에서 문서를 정렬할 필드를 지정합니다. The | |
필수 사항 |
필드에는 내장된 문서 필드와 배열 필드를 지정하기 위한 점이 포함될 수 있습니다.
| |
옵션 | ||
옵션 | 컬렉션에서 읽은 현재 문서의 위치를 기준으로 하한 및 상한 경계가 지정되는 창입니다. 창 경계는 하한 및 상한 문자열 또는 정수를 포함하는 두 요소 배열을 사용하여 지정됩니다. 다음을 사용하세요.
문서 창 예시를 참조하세요. | |
옵션 | ||
옵션 | 시간 범위 창 경계의 단위를 지정합니다. 다음 문자열 중 하나로 설정할 수 있습니다.
생략할 경우 기본값으로 설정된 숫자 범위 창 경계가 사용됩니다. 시간 범위 창 예시를 참조하세요. |
팁
행동
$setWindowFields 단계는 기존 문서에 새 필드를 추가합니다. 집계 연산에 하나 이상의 $setWindowFields 단계를 포함할 수 있습니다.
MongoDB 5.3 트랜잭션 및 "snapshot" 읽기 고려와 함께 $setWindowFields 단계를 사용할 수 있습니다.
The $setWindowFields stage doesn't guarantee the order of the returned documents. Although the stage sorts the documents within each partition by sortBy, that ordering affects only how the stage determines the windows, not the order of the documents it returns. To guarantee a particular output order, use a $sort stage.
창 연산자
이러한 연산자는 $setWindowFields 단계와 함께 사용할 수 있습니다.
- 누산기 연산자:
$addToSet,$avg,$bottom,$bottomN,$count,$covariancePop,$covarianceSamp,$derivative,$expMovingAvg,$firstN,$integral,$lastN,$max,$maxN,$median,$min,$minN,$percentile,$push,$stdDevSamp,$stdDevPop,$sum,$top,$topN.
- 간격 채우기 연산자 :
$linearFill,$locf.
제한 사항
다음은 $setWindowFields 단계에 대한 제한 사항입니다.
MongoDB 5.3 이전에는
$setWindowFields단계를 사용할 수 없습니다.트랜잭션 내.
"snapshot"읽기 고려 문제가 있습니다.
범위 창의 경우 지정된 범위의 숫자만 창에 포함됩니다. 누락된 값, 정의되지 않은 값,
null값은 제외됩니다.시간 범위 창:
창에는 날짜 및 시간 유형만 포함됩니다.
숫자 경계 값은 정수여야 합니다. 예를 들어 2시간은 경계로 사용할 수는 있지만 1.5시간은 사용할 수 없습니다.
예시
이 페이지의 예시는 sample_mflix 데이터 세트의 데이터를 사용합니다. 이 데이터 세트를 자체 관리형 MongoDB 배포서버에 로드하는 방법에 대한 자세한 내용은 샘플 데이터세트 로드를 참조하세요. 샘플 데이터베이스를 수정한 경우, 이 페이지의 예시를 실행하려면 데이터베이스를 제거하고 다시 생성해야 할 수 있습니다.
문서 창 예시
문서 창을 사용하여 각 등급에 대한 누적 런타임 가져오기
이 예시에서는 $setWindowFields의 문서 창을 사용하여 각 rated 값에 대한 누적 runtime을 출력합니다. 예시 출력에서 cumulativeRuntimeForRating 필드는 각 등급에 대한 누적 runtime을 보여줍니다.
db.movies.aggregate( [ { $match: { metacritic: { $gt: 85 }, year: { $gte: 1993, $lte: 1995 } } }, { $project: { _id: 0, title: 1, rated: 1, released: 1, runtime: 1 } }, { $setWindowFields: { partitionBy: "$rated", sortBy: { released: 1 }, output: { cumulativeRuntimeForRating: { $sum: "$runtime", window: { documents: [ "unbounded", "current" ] } } } } }] )[ { rated: 'G', title: 'Toy Story', released: ISODate('1995-11-22T00:00:00.000Z'), runtime: 81, cumulativeRuntimeForRating: 81 }, { rated: 'PG', title: 'Little Women', released: ISODate('1994-12-25T00:00:00.000Z'), runtime: 115, cumulativeRuntimeForRating: 115 }, { rated: 'PG-13', title: 'The Fugitive', released: ISODate('1993-08-06T00:00:00.000Z'), runtime: 130, cumulativeRuntimeForRating: 130 }, { rated: 'PG-13', title: 'King of the Hill', released: ISODate('1993-08-20T00:00:00.000Z'), runtime: 103, cumulativeRuntimeForRating: 233 }, { runtime: 133, rated: 'PG-13', title: 'Quiz Show', released: ISODate('1994-10-07T00:00:00.000Z'), cumulativeRuntimeForRating: 366 }, { rated: 'PG-13', title: 'Hoop Dreams', released: ISODate('1994-10-14T00:00:00.000Z'), runtime: 170, cumulativeRuntimeForRating: 536 }, { runtime: 195, rated: 'R', title: "Schindler's List", released: ISODate('1994-02-04T00:00:00.000Z'), cumulativeRuntimeForRating: 195 }, { runtime: 121, rated: 'R', title: 'The Piano', released: ISODate('1994-02-11T00:00:00.000Z'), cumulativeRuntimeForRating: 316 }, { rated: 'R', title: 'Pulp Fiction', released: ISODate('1994-10-14T00:00:00.000Z'), runtime: 154, cumulativeRuntimeForRating: 470 }, { runtime: 119, title: 'Crumb', released: ISODate('1995-04-28T00:00:00.000Z'), rated: 'R', cumulativeRuntimeForRating: 589 }, { rated: 'R', title: 'To Die For', released: ISODate('1995-10-06T00:00:00.000Z'), runtime: 106, cumulativeRuntimeForRating: 695 }]예시:
partitionBy: "$rated"는 컬렉션의 문서를rated로 분할합니다. 파티션은G,PG,PG-13,R입니다.sortBy: { released: 1 }각 파티션의 문서를released별로 오름차순(1)으로 정렬 하므로 가장 이른released날짜가 먼저 표시됩니다.
문서 창을 사용해 연도별 누적 런타임 가져오기
이 예시에서는 $setWindowFields의 문서 창을 사용하여 released의 각 $year에 대한 runtime을 출력합니다. 예시 출력에서 cumulativeRuntimeForYear 필드는 각 연도의 누적 runtime을 보여줍니다.
db.movies.aggregate( [ { $match: { metacritic: { $gt: 85 }, year: { $gte: 1993, $lte: 1995 } } }, { $project: { _id: 0, title: 1, released: 1, runtime: 1 } }, { $setWindowFields: { partitionBy: { $year: "$released" }, sortBy: { released: 1 }, output: { cumulativeRuntimeForYear: { $sum: "$runtime", window: { documents: [ "unbounded", "current" ] } } } } }] )[ { title: 'The Fugitive', released: ISODate('1993-08-06T00:00:00.000Z'), runtime: 130, cumulativeRuntimeForYear: 130 }, { title: 'King of the Hill', released: ISODate('1993-08-20T00:00:00.000Z'), runtime: 103, cumulativeRuntimeForYear: 233 }, { runtime: 195, title: "Schindler's List", released: ISODate('1994-02-04T00:00:00.000Z'), cumulativeRuntimeForYear: 195 }, { runtime: 121, title: 'The Piano', released: ISODate('1994-02-11T00:00:00.000Z'), cumulativeRuntimeForYear: 316 }, { runtime: 133, title: 'Quiz Show', released: ISODate('1994-10-07T00:00:00.000Z'), cumulativeRuntimeForYear: 449 }, { title: 'Hoop Dreams', released: ISODate('1994-10-14T00:00:00.000Z'), runtime: 170, cumulativeRuntimeForYear: 619 }, { title: 'Pulp Fiction', released: ISODate('1994-10-14T00:00:00.000Z'), runtime: 154, cumulativeRuntimeForYear: 773 }, { title: 'Little Women', released: ISODate('1994-12-25T00:00:00.000Z'), runtime: 115, cumulativeRuntimeForYear: 888 }, { runtime: 119, title: 'Crumb', released: ISODate('1995-04-28T00:00:00.000Z'), cumulativeRuntimeForYear: 119 }, { title: 'To Die For', released: ISODate('1995-10-06T00:00:00.000Z'), runtime: 106, cumulativeRuntimeForYear: 225 }, { title: 'Toy Story', released: ISODate('1995-11-22T00:00:00.000Z'), runtime: 81, cumulativeRuntimeForYear: 306 }]예시:
문서 창을 사용하여 연도별 이동 평균 런타임 가져오기
이 예시에서는 $setWindowFields의 문서 창을 사용하여 이동 평균 runtime을 출력합니다. 예시 출력에서 averageRuntime 필드는 이동 평균 runtime을 보여줍니다.
db.movies.aggregate( [ { $match: { metacritic: { $gt: 85 }, year: { $gte: 1993, $lte: 1995 } } }, { $project: { _id: 0, title: 1, released: 1, runtime: 1 } }, { $setWindowFields: { partitionBy: { $year: "$released" }, sortBy: { released: 1 }, output: { averageRuntime: { $avg: "$runtime", window: { documents: [ -1, 0 ] } } } } }] )[ { title: 'The Fugitive', released: ISODate('1993-08-06T00:00:00.000Z'), runtime: 130, averageRuntime: 130 }, { title: 'King of the Hill', released: ISODate('1993-08-20T00:00:00.000Z'), runtime: 103, averageRuntime: 116.5 }, { runtime: 195, title: "Schindler's List", released: ISODate('1994-02-04T00:00:00.000Z'), averageRuntime: 195 }, { runtime: 121, title: 'The Piano', released: ISODate('1994-02-11T00:00:00.000Z'), averageRuntime: 158 }, { runtime: 133, title: 'Quiz Show', released: ISODate('1994-10-07T00:00:00.000Z'), averageRuntime: 127 }, { title: 'Hoop Dreams', released: ISODate('1994-10-14T00:00:00.000Z'), runtime: 170, averageRuntime: 151.5 }, { title: 'Pulp Fiction', released: ISODate('1994-10-14T00:00:00.000Z'), runtime: 154, averageRuntime: 162 }, { title: 'Little Women', released: ISODate('1994-12-25T00:00:00.000Z'), runtime: 115, averageRuntime: 134.5 }, { runtime: 119, title: 'Crumb', released: ISODate('1995-04-28T00:00:00.000Z'), averageRuntime: 119 }, { title: 'To Die For', released: ISODate('1995-10-06T00:00:00.000Z'), runtime: 106, averageRuntime: 112.5 }, { title: 'Toy Story', released: ISODate('1995-11-22T00:00:00.000Z'), runtime: 81, averageRuntime: 93.5 }]예시:
문서 창을 사용하여 연도별 누적 및 최대 런타임 가져오기
이 예시에서는 $setWindowFields의 문서 창을 사용하여 released의 각 $year에 대한 누적 및 최대 runtime 값을 출력합니다. 예시 출력에서 cumulativeRuntimeForYear 필드는 누적 runtime을 보여주고, maximumRuntimeForYear 필드는 최대 runtime을 보여줍니다.
db.movies.aggregate( [ { $match: { metacritic: { $gt: 85 }, year: { $gte: 1993, $lte: 1995 } } }, { $project: { _id: 0, title: 1, released: 1, runtime: 1 } }, { $setWindowFields: { partitionBy: { $year: "$released" }, sortBy: { released: 1 }, output: { cumulativeRuntimeForYear: { $sum: "$runtime", window: { documents: [ "unbounded", "current" ] } }, maximumRuntimeForYear: { $max: "$runtime", window: { documents: [ "unbounded", "unbounded" ] } } } } }] )[ { title: 'The Fugitive', released: ISODate('1993-08-06T00:00:00.000Z'), runtime: 130, cumulativeRuntimeForYear: 130, maximumRuntimeForYear: 130 }, { title: 'King of the Hill', released: ISODate('1993-08-20T00:00:00.000Z'), runtime: 103, cumulativeRuntimeForYear: 233, maximumRuntimeForYear: 130 }, { runtime: 195, title: "Schindler's List", released: ISODate('1994-02-04T00:00:00.000Z'), cumulativeRuntimeForYear: 195, maximumRuntimeForYear: 195 }, { runtime: 121, title: 'The Piano', released: ISODate('1994-02-11T00:00:00.000Z'), cumulativeRuntimeForYear: 316, maximumRuntimeForYear: 195 }, { runtime: 133, title: 'Quiz Show', released: ISODate('1994-10-07T00:00:00.000Z'), cumulativeRuntimeForYear: 449, maximumRuntimeForYear: 195 }, { title: 'Hoop Dreams', released: ISODate('1994-10-14T00:00:00.000Z'), runtime: 170, cumulativeRuntimeForYear: 619, maximumRuntimeForYear: 195 }, { title: 'Pulp Fiction', released: ISODate('1994-10-14T00:00:00.000Z'), runtime: 154, cumulativeRuntimeForYear: 773, maximumRuntimeForYear: 195 }, { title: 'Little Women', released: ISODate('1994-12-25T00:00:00.000Z'), runtime: 115, cumulativeRuntimeForYear: 888, maximumRuntimeForYear: 195 }, { runtime: 119, title: 'Crumb', released: ISODate('1995-04-28T00:00:00.000Z'), cumulativeRuntimeForYear: 119, maximumRuntimeForYear: 119 }, { title: 'To Die For', released: ISODate('1995-10-06T00:00:00.000Z'), runtime: 106, cumulativeRuntimeForYear: 225, maximumRuntimeForYear: 119 }, { title: 'Toy Story', released: ISODate('1995-11-22T00:00:00.000Z'), runtime: 81, cumulativeRuntimeForYear: 306, maximumRuntimeForYear: 119 }]예시:
partitionBy: { $year: "$released" }에서$year를 기준으로 사용해 컬렉션의 문서를 파티셔닝released합니다.1993,1994,1995에 대한 파티션이 있습니다.sortBy: { released: 1 }각 파티션의 문서를released별로 오름차순(1)으로 정렬 하므로 가장 이른released날짜가 먼저 표시됩니다.output:cumulativeRuntimeForYear필드를 각 연도의 누적runtime(으)로 설정합니다.연도별로
maximumRuntimeForYear필드를 최대runtime로 설정합니다.
범위 윈도우 예시
이 예시에서는 $setWindowFields의 범위 창을 사용하여 현재 문서의 runtime 값으로부터 ±10분 범위 내에 출시된 영화에 대한 runtime 값의 합계를 반환합니다. 예시 출력에서 runtimeFromSimilarMovies 필드는 창에 있는 문서에 대한 runtime 값의 합계를 보여줍니다.
db.movies.aggregate( [ { $match: { metacritic: { $gt: 85 }, year: { $gte: 1993, $lte: 1995 } } }, { $project: { _id: 0, title: 1, rated: 1, runtime: 1 } }, { $setWindowFields: { partitionBy: "$rated", sortBy: { runtime: 1 }, output: { runtimeFromSimilarMovies: { $sum: "$runtime", window: { range: [ -10, 10 ] } } } } }] )[ { rated: 'G', title: 'Toy Story', runtime: 81, runtimeFromSimilarMovies: 81 }, { rated: 'PG', title: 'Little Women', runtime: 115, runtimeFromSimilarMovies: 115 }, { rated: 'PG-13', title: 'King of the Hill', runtime: 103, runtimeFromSimilarMovies: 103 }, { rated: 'PG-13', title: 'The Fugitive', runtime: 130, runtimeFromSimilarMovies: 263 }, { runtime: 133, rated: 'PG-13', title: 'Quiz Show', runtimeFromSimilarMovies: 263 }, { rated: 'PG-13', title: 'Hoop Dreams', runtime: 170, runtimeFromSimilarMovies: 170 }, { rated: 'R', title: 'To Die For', runtime: 106, runtimeFromSimilarMovies: 106 }, { runtime: 119, title: 'Crumb', rated: 'R', runtimeFromSimilarMovies: 240 }, { runtime: 121, rated: 'R', title: 'The Piano', runtimeFromSimilarMovies: 240 }, { rated: 'R', title: 'Pulp Fiction', runtime: 154, runtimeFromSimilarMovies: 154 }, { runtime: 195, rated: 'R', title: "Schindler's List", runtimeFromSimilarMovies: 195 }]예시:
시간 범위 창 예시
상한이 양수인 시간 범위 창 사용
다음 예시에서는 양수 상한 시간 범위 단위가 $setWindowFields인 창을 사용합니다. 파이프라인은 지정된 시간 범위와 일치하는 각 rated 값에 대해 released 값의 배열을 출력합니다. 예시 출력에서 recentReleases 필드는 released 값의 배열을 보여줍니다.
db.movies.aggregate( [ { $match: { metacritic: { $gt: 85 }, year: { $gte: 1993, $lte: 1995 } } }, { $project: { _id: 0, title: 1, rated: 1, released: 1 } }, { $setWindowFields: { partitionBy: "$rated", sortBy: { released: 1 }, output: { recentReleases: { $push: "$released", window: { range: [ "unbounded", 10 ], unit: "month" } } } } }] )[ { rated: 'G', title: 'Toy Story', released: ISODate('1995-11-22T00:00:00.000Z'), recentReleases: [ ISODate('1995-11-22T00:00:00.000Z') ] }, { rated: 'PG', title: 'Little Women', released: ISODate('1994-12-25T00:00:00.000Z'), recentReleases: [ ISODate('1994-12-25T00:00:00.000Z') ] }, { rated: 'PG-13', title: 'The Fugitive', released: ISODate('1993-08-06T00:00:00.000Z'), recentReleases: [ ISODate('1993-08-06T00:00:00.000Z'), ISODate('1993-08-20T00:00:00.000Z') ] }, { rated: 'PG-13', title: 'King of the Hill', released: ISODate('1993-08-20T00:00:00.000Z'), recentReleases: [ ISODate('1993-08-06T00:00:00.000Z'), ISODate('1993-08-20T00:00:00.000Z') ] }, { rated: 'PG-13', title: 'Quiz Show', released: ISODate('1994-10-07T00:00:00.000Z'), recentReleases: [ ISODate('1993-08-06T00:00:00.000Z'), ISODate('1993-08-20T00:00:00.000Z'), ISODate('1994-10-07T00:00:00.000Z'), ISODate('1994-10-14T00:00:00.000Z') ] }, { rated: 'PG-13', title: 'Hoop Dreams', released: ISODate('1994-10-14T00:00:00.000Z'), recentReleases: [ ISODate('1993-08-06T00:00:00.000Z'), ISODate('1993-08-20T00:00:00.000Z'), ISODate('1994-10-07T00:00:00.000Z'), ISODate('1994-10-14T00:00:00.000Z') ] }, { rated: 'R', title: "Schindler's List", released: ISODate('1994-02-04T00:00:00.000Z'), recentReleases: [ ISODate('1994-02-04T00:00:00.000Z'), ISODate('1994-02-11T00:00:00.000Z'), ISODate('1994-10-14T00:00:00.000Z') ] }, { rated: 'R', title: 'The Piano', released: ISODate('1994-02-11T00:00:00.000Z'), recentReleases: [ ISODate('1994-02-04T00:00:00.000Z'), ISODate('1994-02-11T00:00:00.000Z'), ISODate('1994-10-14T00:00:00.000Z') ] }, { rated: 'R', title: 'Pulp Fiction', released: ISODate('1994-10-14T00:00:00.000Z'), recentReleases: [ ISODate('1994-02-04T00:00:00.000Z'), ISODate('1994-02-11T00:00:00.000Z'), ISODate('1994-10-14T00:00:00.000Z'), ISODate('1995-04-28T00:00:00.000Z') ] }, { title: 'Crumb', released: ISODate('1995-04-28T00:00:00.000Z'), rated: 'R', recentReleases: [ ISODate('1994-02-04T00:00:00.000Z'), ISODate('1994-02-11T00:00:00.000Z'), ISODate('1994-10-14T00:00:00.000Z'), ISODate('1995-04-28T00:00:00.000Z'), ISODate('1995-10-06T00:00:00.000Z') ] }, { rated: 'R', title: 'To Die For', released: ISODate('1995-10-06T00:00:00.000Z'), recentReleases: [ ISODate('1994-02-04T00:00:00.000Z'), ISODate('1994-02-11T00:00:00.000Z'), ISODate('1994-10-14T00:00:00.000Z'), ISODate('1995-04-28T00:00:00.000Z'), ISODate('1995-10-06T00:00:00.000Z') ] }]예시:
partitionBy: "$rated"는 컬렉션의 문서를rated로 분할합니다. 파티션은G,PG,PG-13,R입니다.sortBy: { released: 1 }각 파티션의 문서를released별로 오름차순(1)으로 정렬 하므로 가장 이른released날짜가 먼저 표시됩니다.
$push는 파티션의 시작 부분과 현재 문서의released값에10개월을 더한 범위 내에서released값을 포함하는 문서 사이에 있는 문서들에 대한released값 배열을 반환합니다.
음수 상한이 있는 시간 범위 창 사용
다음 예시에서는 음수 상한 시간 범위 단위가 $setWindowFields인 창을 사용합니다. 파이프라인은 지정된 시간 범위와 일치하는 각 rated 값에 대해 released 값의 배열을 출력합니다. 예시 출력에서 recentReleases 필드는 released 값의 배열을 보여줍니다.
db.movies.aggregate( [ { $match: { metacritic: { $gt: 85 }, year: { $gte: 1993, $lte: 1995 } } }, { $project: { _id: 0, title: 1, rated: 1, released: 1 } }, { $setWindowFields: { partitionBy: "$rated", sortBy: { released: 1 }, output: { recentReleases: { $push: "$released", window: { range: [ "unbounded", -10 ], unit: "month" } } } } }] )[ { rated: 'G', title: 'Toy Story', released: ISODate('1995-11-22T00:00:00.000Z'), recentReleases: [] }, { rated: 'PG', title: 'Little Women', released: ISODate('1994-12-25T00:00:00.000Z'), recentReleases: [] }, { rated: 'PG-13', title: 'The Fugitive', released: ISODate('1993-08-06T00:00:00.000Z'), recentReleases: [] }, { rated: 'PG-13', title: 'King of the Hill', released: ISODate('1993-08-20T00:00:00.000Z'), recentReleases: [] }, { rated: 'PG-13', title: 'Quiz Show', released: ISODate('1994-10-07T00:00:00.000Z'), recentReleases: [ ISODate('1993-08-06T00:00:00.000Z'), ISODate('1993-08-20T00:00:00.000Z') ] }, { rated: 'PG-13', title: 'Hoop Dreams', released: ISODate('1994-10-14T00:00:00.000Z'), recentReleases: [ ISODate('1993-08-06T00:00:00.000Z'), ISODate('1993-08-20T00:00:00.000Z') ] }, { rated: 'R', title: "Schindler's List", released: ISODate('1994-02-04T00:00:00.000Z'), recentReleases: [] }, { rated: 'R', title: 'The Piano', released: ISODate('1994-02-11T00:00:00.000Z'), recentReleases: [] }, { rated: 'R', title: 'Pulp Fiction', released: ISODate('1994-10-14T00:00:00.000Z'), recentReleases: [] }, { title: 'Crumb', released: ISODate('1995-04-28T00:00:00.000Z'), rated: 'R', recentReleases: [ ISODate('1994-02-04T00:00:00.000Z'), ISODate('1994-02-11T00:00:00.000Z') ] }, { rated: 'R', title: 'To Die For', released: ISODate('1995-10-06T00:00:00.000Z'), recentReleases: [ ISODate('1994-02-04T00:00:00.000Z'), ISODate('1994-02-11T00:00:00.000Z'), ISODate('1994-10-14T00:00:00.000Z') ] }]예시:
partitionBy: "$rated"는 컬렉션의 문서를rated로 분할합니다. 파티션은G,PG,PG-13,R입니다.sortBy: { released: 1 }각 파티션의 문서를released별로 오름차순(1)으로 정렬 하므로 가장 이른released날짜가 먼저 표시됩니다.
$push는 파티션의 시작 부분과 현재 문서의released값에서10개월을 뺀 범위 내에서released값을 포함하는 문서 사이에 있는 문서들에 대한released값 배열을 반환합니다.
이전 값과의 비교 예시
다음 예시 $shift 연산자 및 $set 단계와 함께 $setWindowFields 를 사용하여 컬렉션의 필드를 비교합니다. 예시 출력에서 runtimeComparison 필드는 비교 결과를 보여줍니다.
db.movies.aggregate( [ { $match: { metacritic: { $gt: 85 }, year: { $gte: 1993, $lte: 1995 } } }, { $project: { _id: 0, title: 1, rated: 1, released: 1, runtime: 1 } }, { $setWindowFields: { partitionBy: "$rated", sortBy: { released: 1 }, output: { previousRuntime: { $shift: { output: "$runtime", by: -1 } } } } }, { $set: { runtimeComparison: { $cond: [ { $eq: ["$runtime", "$previousRuntime"] }, "same", { $cond: [ { $gt: ["$runtime", "$previousRuntime"] }, "longer", "shorter" ] } ] } } },] )[ { rated: 'G', title: 'Toy Story', released: ISODate('1995-11-22T00:00:00.000Z'), runtime: 81, previousRuntime: null, runtimeComparison: 'longer' }, { rated: 'PG', title: 'Little Women', released: ISODate('1994-12-25T00:00:00.000Z'), runtime: 115, previousRuntime: null, runtimeComparison: 'longer' }, { rated: 'PG-13', title: 'The Fugitive', released: ISODate('1993-08-06T00:00:00.000Z'), runtime: 130, previousRuntime: null, runtimeComparison: 'longer' }, { rated: 'PG-13', title: 'King of the Hill', released: ISODate('1993-08-20T00:00:00.000Z'), runtime: 103, previousRuntime: 130, runtimeComparison: 'shorter' }, { runtime: 133, rated: 'PG-13', title: 'Quiz Show', released: ISODate('1994-10-07T00:00:00.000Z'), previousRuntime: 103, runtimeComparison: 'longer' }, { rated: 'PG-13', title: 'Hoop Dreams', released: ISODate('1994-10-14T00:00:00.000Z'), runtime: 170, previousRuntime: 133, runtimeComparison: 'longer' }, { runtime: 195, rated: 'R', title: "Schindler's List", released: ISODate('1994-02-04T00:00:00.000Z'), previousRuntime: null, runtimeComparison: 'longer' }, { runtime: 121, rated: 'R', title: 'The Piano', released: ISODate('1994-02-11T00:00:00.000Z'), previousRuntime: 195, runtimeComparison: 'shorter' }, { rated: 'R', title: 'Pulp Fiction', released: ISODate('1994-10-14T00:00:00.000Z'), runtime: 154, previousRuntime: 121, runtimeComparison: 'longer' }, { runtime: 119, title: 'Crumb', released: ISODate('1995-04-28T00:00:00.000Z'), rated: 'R', previousRuntime: 154, runtimeComparison: 'shorter' }, { rated: 'R', title: 'To Die For', released: ISODate('1995-10-06T00:00:00.000Z'), runtime: 106, previousRuntime: 119, runtimeComparison: 'shorter' }]예시:
partitionBy: "$rated"는 컬렉션의 문서를rated로 분할하여 각 평점의 계산이 별도로 유지되도록 합니다.sortBy: { released: 1 }각 파티션의 문서를 오름차순(1)으로released기준으로 정렬합니다.output.previousRuntime은$shift연산자 사용하여 동일한 평점 내의 바로 이전 영화에서runtime을 캡처합니다.$set는runtimeComparison라는 새 필드 추가하고previousRuntime와의 비교를 기반으로 해당 필드의 값을longer,shorter또는same로 설정합니다.
다음 WeatherMeasurement 클래스는 날씨 측정값 컬렉션 의 문서를 나타냅니다.
[BsonIgnoreExtraElements]public class WeatherMeasurement{ [BsonId] public ObjectId Id { get; set; } [BsonElement("localityId")] public string LocalityId { get; set; } = null!; [BsonElement("measurementDateTime")] public DateTime MeasurementDateTime { get; set; } [BsonElement("rainfall")] public float Rainfall { get; set; } [BsonElement("temperature")] public float Temperature { get; set; }}MongoDB .NET/ C# 운전자 사용하여 $setWindowFields 집계 파이프라인 에 단계를 추가하려면 PipelineDefinition 객체 에서 UnionWith() 메서드를 호출합니다.
다음 예시 Rainfall 및 Temperature 필드를 사용하여 각 지역의 지난 달 누적 강우량, 이동 평균 기온, 중앙값 온도 및 90백분위 강우량을 계산하는 파이프라인 단계를 만듭니다.
var pipeline = new EmptyPipelineDefinition<WeatherMeasurement>() .SetWindowFields( partitionBy: w => w.LocalityId, sortBy: Builders<WeatherMeasurement>.Sort.Ascending( w => w.MeasurementDateTime), output: o => new { MonthlyRainfall = o.Sum( w => w.Rainfall, RangeWindow.Create( RangeWindow.Months(-1), RangeWindow.Current) ), TemperatureAvg = o.Average( w => w.Temperature, RangeWindow.Create( RangeWindow.Months(-1), RangeWindow.Current) ), MedianTemperature = o.Median( w => w.Temperature, RangeWindow.Create( RangeWindow.Months(-1), RangeWindow.Current) ), NinetiethPercentileRainfall = o.Percentile( w => w.Rainfall, new[] { 0.9 }, RangeWindow.Create( RangeWindow.Months(-1), RangeWindow.Current) ) } );이 페이지의 Node.js 예시에서는 Atlas 샘플 데이터 세트의 sample_weatherdata.data 컬렉션을 사용합니다. 무료 MongoDB Atlas 클러스터를 생성하고 샘플 데이터 세트를 로드하는 방법을 학습하려면 MongoDB Node.js 드라이버 문서의 시작하기를 참조하세요.
MongoDB Node.js 운전자 사용하여 집계 파이프라인 에 $setWindowFields 단계를 추가하려면 파이프라인 객체 에서 $setWindowFields 연산자 사용합니다.
다음 예시는 지난 한 달 동안 고유한 각 callLetters 값에 대해 airTemperature.value의 평균과 waveMeasurement.waves.height의 총계를 계산하는 파이프라인 단계를 만듭니다. 그리고 집계 파이프라인을 실행합니다.
const pipeline = [ { $setWindowFields: { partitionBy: "$callLetters", sortBy: { ts: 1 }, output: { temperatureAvg: { $avg: "$airTemperature.value", window: { range: [-1, "current"], unit: "month" } }, totalWaveHeight: { $sum: "$waveMeasurement.waves.height", window: { range: [-1, "current"], unit: "month" } } } } },];
const cursor = collection.aggregate(pipeline);return cursor;팁
IOT 전력 소비에 대한 추가 예시는 IOT 전력 소비에 대한 추가 예시는 실용적인 MongoDB 집계 전자책을 참조하세요.