AI 에이전트의 경우: 문서 인덱스는 https://www.mongodb.com/ko-kr/docs/llms.txt에서 사용할 수 있으며, 모든 페이지의 마크다운 버전은 어떤 URL 경로에 .md를 추가하여 사용할 수 있습니다.
Docs Menu

$setWindowFields (집계 단계)

$setWindowFields

버전 5.0의 신규 항목입니다.

Performs operations on a specified span of documents in a collection, known as a window, and returns the results based on the chosen window operator.

For example, you can use the $setWindowFields stage to output the:

  • 컬렉션에 있는 두 문서 간의 판매량 차이입니다.

  • 판매 순위.

  • 누적 판매 총액입니다.

  • 데이터를 외부 데이터베이스로 내보내지 않고도 복잡한 시계열 정보를 분석합니다.

The $setWindowFields stage syntax:

{
$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>: { ... }
}
}
}

The $setWindowFields stage takes a document with these fields:

필드
필요성
설명

옵션

Specifies an expression to group the documents. In the $setWindowFields stage, the group of documents is known as a partition. Default is one partition for the entire collection.

Required for some operators (see Restrictions)

파티션에서 문서를 정렬할 필드를 지정합니다. $sort 단계와 동일한 구문을 사용합니다. 기본값은 정렬하지 않습니다.

필수 사항

Specifies the field(s) to append to the documents in the output returned by the $setWindowFields stage. Each field is set to the result returned by the window operator.

A field can contain dots to specify embedded document fields and array fields. The semantics for the embedded document dotted notation in the $setWindowFields stage are the same as the $addFields and $set stages. See embedded document $addFields example and embedded document $set example.

옵션

창 경계 및 매개 변수를 지정합니다. 창 경계는 포괄적입니다. 기본값은 파티션에 있는 모든 문서를 포함하는 바인딩 되지 않은 창입니다.

문서 또는 범위 창을 지정합니다.

옵션

컬렉션에서 읽은 현재 문서의 위치를 기준으로 하한 및 상한 경계가 지정되는 창입니다.

창 경계는 하한 및 상한 문자열 또는 정수를 포함하는 두 요소 배열을 사용하여 지정됩니다. 다음을 사용하세요.

  • 출력의 현재 문서 위치에 대한 "current" 문자열입니다.

  • 파티션의 첫 번째 또는 마지막 문서 위치에 대한 "unbounded" 문자열입니다.

  • 현재 문서를 기준으로 한 위치의 정수입니다. 현재 문서 이전 위치에는 음의 정수를 사용하고, 현재 문서 이후 위치에는 양의 정수를 사용합니다. 0은 현재 문서의 위치를 말합니다.

문서 창 예시를 참조하세요.

옵션

A window where the lower and upper boundaries are defined using a range of values based on the sortBy field in the current document.

윈도우 경계는 하한 및 상한 문자열 또는 숫자를 포함하는 두 요소 배열을 사용하여 지정됩니다. 다음을 사용하세요.

  • 출력의 현재 문서 위치에 대한 "current" 문자열입니다.

  • 파티션의 첫 번째 또는 마지막 문서 위치에 대한 "unbounded" 문자열입니다.

  • 현재 문서의 sortBy 필드 값에 추가할 숫자입니다. sortBy 필드 값이 하한선과 상한선을 모두 포함하는 경우 문서가 윈도우에 있습니다.

범위 창 예시를 참조하세요.

옵션

시간 범위 창 경계의 단위를 지정합니다. 다음 문자열 중 하나로 설정할 수 있습니다.

  • "year"

  • "quarter"

  • "month"

  • "week"

  • "day"

  • "hour"

  • "minute"

  • "second"

  • "millisecond"

If omitted, default numeric range window boundaries are used.

시간 범위 창 예시를 참조하세요.

The $setWindowFields stage appends new fields to existing documents. You can include one or more $setWindowFields stages in an aggregation operation.

Starting in MongoDB 5.3, you can use the $setWindowFields stage with transactions and the "snapshot" read concern.

$setWindowFields 단계는 반환된 문서의 순서를 보장하지 않습니다.

These operators can be used with the $setWindowFields stage:

버전 8.3에 추가 되었습니다.

$setWindowsFields 작업에서 explain 를 실행 출력에는 사용 중인 추적 메모리의 최대 바이트 수가 포함된 peakTrackedMemBytes 필드 포함됩니다. 자세한 내용은 explain.executionStats.peakTrackedMemBytes를 참조하세요.

Restrictions for the $setWindowFields stage:

  • Before MongoDB 5.3, the $setWindowFields stage cannot be used:

  • sortBy is required for:

  • 범위 창에서는 모든 sortBy 값이 숫자여야 합니다.

  • 시간 범위 창에서는 모든 sortBy 값이 날짜여야 합니다.

  • 범위 및 시간 범위 창에는 sortBy 필드가 하나만 포함될 수 있으며 정렬은 오름차순이어야 합니다.

  • You cannot specify both a documents window and a range window.

  • 이러한 연산자는 암시적 창을 사용하며 다음과 같은 창 옵션을 지정하면 오류를 반환합니다.

    • Rank operators.

    • $shift 연산자를 사용하세요.

  • For range windows, only numbers in the specified range are included in the window. Missing, undefined, and null values are excluded.

  • For time range windows:

    • 창에는 날짜 및 시간 유형만 포함됩니다.

    • 숫자 경계 값은 정수여야 합니다. 예를 들어 2시간은 경계로 사용할 수는 있지만 1.5시간은 사용할 수 없습니다.

  • 빈 창 또는 호환되지 않는 값을 가진 창(예시: 문자열에 $sum 사용)의 경우 반환되는 값은 연산자에 따라 달라집니다.

    • $count 및 $sum 의 경우 반환되는 값은 0 입니다.

    • $addToSet 및 $push 의 경우 반환되는 값은 빈 배열입니다.

    • 다른 모든 연산자의 경우 반환되는 값은 null입니다.

이 페이지의 예시는 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 날짜가 먼저 정렬됩니다.

  • output:

    • cumulativeRuntimeForRating 필드 파티션의 이전 값에 연속적으로 추가하여 증가하는 각 rated 값에 대한 누적 runtime로 설정합니다.

    • Calculates the cumulative runtime using the $sum operator run in a documents window.

      The window contains documents between an unbounded lower limit and the current document. This means $sum returns the cumulative runtime for the documents between the beginning of the partition and the current document.

이 예시 $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
}
]

예시:

  • partitionBy: { $year: "$released" } partitions the documents in the collection by $year in released. There are partitions for 1993, 1994, and 1995.

  • sortBy: { released: 1 } 각 파티션의 문서를 released별로 오름차순(1)으로 정렬하므로 가장 이른 released 날짜가 먼저 정렬됩니다.

  • output:

    • cumulativeRuntimeForYear 필드를 각 연도의 누적 runtime로 설정합니다. 이 값은 파티션의 이전 값에 연속적으로 추가되어 증가합니다.

    • Calculates the cumulative runtime using the $sum operator run in a documents window.

      The window contains documents between an unbounded lower limit and the current document. This means $sum returns the cumulative runtime for the documents between the beginning of the partition and the current document.

이 예시 $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
}
]

예시:

  • partitionBy: { $year: "$released" } partitions the documents in the collection by $year in released. There are partitions for 1993, 1994, and 1995.

  • sortBy: { released: 1 } 각 파티션의 문서를 released별로 오름차순(1)으로 정렬하므로 가장 이른 released 날짜가 먼저 정렬됩니다.

  • output:

    • averageRuntime 필드를 연도별 이동 평균 runtime(으)로 설정합니다.

    • Calculates the moving average runtime using the $avg operator run in a documents window.

      The window contains documents between -1 and 0. This means $avg returns the moving average runtime between the document before the current document (-1) and the current document (0) in the partition.

이 예시 $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" } partitions the documents in the collection by $year in released. There are partitions for 1993, 1994, and 1995.

  • sortBy: { released: 1 } 각 파티션의 문서를 released별로 오름차순(1)으로 정렬하므로 가장 이른 released 날짜가 먼저 정렬됩니다.

  • output:

    • cumulativeRuntimeForYear 필드를 각 연도의 누적 runtime(으)로 설정합니다.

    • Calculates the cumulative runtime using the $sum operator run in a documents window.

      The window contains documents between an unbounded lower limit and the current document. This means $sum returns the cumulative runtime for the documents between the beginning of the partition and the current document.

    • 연도별로 maximumRuntimeForYear 필드를 최대 runtime 로 설정합니다.

    • Calculates the maximum runtime of all the documents using the $max operator run in a documents window.

      이 창 unbounded 하한과 upper 한도 사이의 문서가 포함되어 있습니다. 즉, $max는 파티션의 문서에 대해 최대 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
}
]

예시:

  • partitionBy: "$rated" 컬렉션 의 문서를 rated로 파티셔닝합니다. 파티션은 G, PG, PG-13, R입니다.

  • sortBy: { runtime: 1 } 각 파티션의 문서를 runtime별로 오름차순(1)으로 정렬하므로 가장 짧은 runtime이 먼저 정렬됩니다.

  • output runtimeFromSimilarMovies 필드를 범위 창에 있는 문서의 runtime 값의 합계로 설정합니다.

    • The window contains documents between a lower limit of -10 and an upper limit of 10. The range is inclusive.

    • $sum는 현재 문서의 runtime 값에서 플러스 또는 마이너스 10분 범위 에 포함된 runtime 값의 합계를 반환합니다.

다음 예시 양의 상한 시간 범위 단위가 $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 날짜가 먼저 정렬됩니다.

  • output:

    • recentReleases 필드 각 rated 파티션의 문서에 대한 released 값의 배열 로 설정합니다. 배열 요소는 배열 의 이전 요소에 추가되어 확장됩니다.

    • $push를 사용하여 범위 창에 있는 문서에서 released 값의 배열을 반환합니다.

  • The window contains documents between an unbounded lower limit and an upper limit set to 10 (10 months after the current document's released value) using a time range unit.

  • $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 날짜가 먼저 정렬됩니다.

  • output:

    • recentReleases 필드 각 rated 파티션의 문서에 대한 released 값의 배열 로 설정합니다. 배열 요소는 배열 의 이전 요소에 추가되어 확장됩니다.

    • $push를 사용하여 범위 창에 있는 문서에서 released 값의 배열을 반환합니다.

  • The window contains documents between an unbounded lower limit and an upper limit set to -10 (10 months before the current document's released value) using a time range unit.

  • $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 } sorts the documents in each partition by released in ascending order (1).

  • output.previousRuntime $shift 연산자 사용하여 동일한 등급 내의 바로 이전 영화에서 runtime를 캡처합니다.

  • $set 는 runtimeComparison라는 새 필드 추가하고 previousRuntime와의 비교를 기반으로 해당 필드의 값을 longer, shorter 또는 same 로 설정합니다.

팁

IOT 전력 소비에 대한 추가 예시는 IOT 전력 소비에 대한 추가 예시는 실용적인 MongoDB 집계 전자책을 참조하세요.