정의
$zip출력 배열의 첫 번째 요소가 첫 번째 입력 배열의 첫 번째 요소, 두 번째 입력 배열의 첫 번째 요소 등을 포함하는 배열이 되도록 입력 배열의 배열을 바꿉니다.
For example,
$zipwould transform[ [ 1, 2, 3 ], [ "a", "b", "c" ] ]into[ [ 1, "a" ], [ 2, "b" ], [ 3, "c" ] ].$zip의 구문은 다음과 같습니다:{ $zip: { inputs: [ <array expression1>, ... ], useLongestLength: <boolean>, defaults: <array expression> } } 피연산자설명inputsuseLongestLength가장 긴 배열의 길이가 출력 배열의 배열 수를 결정하는지 여부를 지정하는 부울입니다.
기본값은
false이며 가장 짧은 배열 길이에 따라 출력 배열의 배열 수가 결정됩니다.defaultsAn array of default element values to use if the input arrays have different lengths. You must specify
useLongestLength: truealong with this field, or else$zipwill return an error.If
useLongestLength: truebutdefaultsis empty or not specified,$zipusesnullas the default value.If specifying a non-empty
defaults, you must specify a default for each input array or else$zipwill return an error.
행동
The input arrays do not need to be of the same length. By default, the output array has the length of the shortest input array, but the useLongestLength option instructs $zip to output an array as long as the longest input array.
예시 | 결과 | |||||||
|---|---|---|---|---|---|---|---|---|
| | |||||||
| | |||||||
| | |||||||
|
결과는 |
예시
매트릭스 전치
컬렉션 matrices에는 다음 문서가 포함되어 있습니다.
db.matrices.insertMany([ { matrix: [[1, 2], [2, 3], [3, 4]] }, { matrix: [[8, 7], [7, 6], [5, 4]] }, ])
이 컬렉션에 있는 각 3x2 매트릭스 전치를 계산하려면 다음 집계 작업을 사용하면 됩니다.
db.matrices.aggregate([{ $project: { _id: false, transposed: { $zip: { inputs: [ { $arrayElemAt: [ "$matrix", 0 ] }, { $arrayElemAt: [ "$matrix", 1 ] }, { $arrayElemAt: [ "$matrix", 2 ] }, ] } } } }])
그러면 다음과 같은 2x3 매트릭스가 반환됩니다.
{ "transposed" : [ [ 1, 2, 3 ], [ 2, 3, 4 ] ] } { "transposed" : [ [ 8, 7, 5 ], [ 7, 6, 4 ] ] }
인덱스 필터링 및 보존
$zip을 $filter와 함께 사용하여 배열에서 요소의 하위 집합을 가져와서 유지되는 각 요소와 함께 원래 인덱스를 저장할 수 있습니다.
pages 컬렉션에는 다음 문서가 포함되어 있습니다.
db.pages.insertOne( { "category": "unix", "pages": [ { "title": "awk for beginners", reviews: 5 }, { "title": "sed for newbies", reviews: 0 }, { "title": "grep made simple", reviews: 2 }, ] } )
다음 집계 파이프라인은 먼저 pages 배열의 요소를 인덱스와 함께 압축한 다음 리뷰가 하나 이상 있는 페이지만 필터링합니다.
db.pages.aggregate([{ $project: { _id: false, pages: { $filter: { input: { $zip: { inputs: [ "$pages", { $range: [0, { $size: "$pages" }] } ] } }, as: "pageWithIndex", cond: { $let: { vars: { page: { $arrayElemAt: [ "$$pageWithIndex", 0 ] } }, in: { $gte: [ "$$page.reviews", 1 ] } } } } } } }])
그러면 다음 문서가 반환됩니다.
{ "pages" : [ [ { "title" : "awk for beginners", "reviews" : 5 }, 0 ], [ { "title" : "grep made simple", "reviews" : 2 }, 2 ] ] }