정의
구문
$unionWith 단계에는 다음과 같은 구문이 있습니다.
{ $unionWith: { coll: "<collection>", pipeline: [ <stage1>, ... ] } }처리하지 않고 지정된 collection의 모든 문서를 포함하려면 간단한 양식을 사용할 수 있습니다.
{ $unionWith: "<collection>" } // Include all documents from the specified collection$unionWith 단계에서는 다음 필드가 있는 문서를 사용합니다.
필드 | 필요성 | 설명 |
|---|---|---|
| 결과 집합에 포함하려는 파이프라인 결과가 있는 컬렉션 또는 보기입니다.
| |
| 입력 문서에 적용할 집계 파이프라인입니다.
파이프라인에 |
$unionWith 작업은 다음 SQL 문에 해당합니다.
SELECT *FROM Collection1WHERE ...UNION ALLSELECT *FROM Collection2WHERE ...고려 사항
중복 결과
이전 단계와 $unionWith 단계의 결과를 합친 결과에는 중복이 포함될 수 있습니다.
예시, 다음 집계는 movies 컬렉션에 대한 두 쿼리의 title 필드 프로젝션 결과를 결합합니다. 결과 집합에 중복된 항목이 포함되어 있습니다.
db.movies.aggregate( [ { $match: { runtime: { $gt: 1000 } } }, { $project: { title: 1, _id: 0 } }, { $unionWith: { coll: "movies", pipeline: [ { $match: { runtime: { $gt: 1000 } } }, { $project: { title: 1, _id: 0 } } ] } }] )[ { title: 'Centennial' }, { title: 'Baseball' }, { title: 'Centennial' }, { title: 'Baseball' }]중복 항목을 제거하려면 $group 단계를 포함하여 title 필드별로 그룹화할 수 있습니다. 집합에 더 이상 중복된 항목이 포함되지 않는 경우:
db.movies.aggregate( [ { $match: { runtime: { $gt: 1000 } } }, { $project: { title: 1, _id: 0 } }, { $unionWith: { coll: "movies", pipeline: [ { $match: { runtime: { $gt: 1000 } } }, { $project: { title: 1, _id: 0 } } ] } }, { $group: { _id: "$title" } }, { $sort: { _id: 1 } }] )[ { _id: 'Baseball' }, { _id: 'Centennial' }]데이터 정렬
db.collection.aggregate() 에 collation 문서 포함된 경우 작업은 해당 데이터 정렬을 사용하고 다른 데이터 정렬은 무시합니다.
db.collection.aggregate() 에 collation 문서가 포함되어 있지 않은 경우 db.collection.aggregate() 메서드는 db.collection.aggregate() 가 실행되는 최상위 컬렉션/뷰에 대한 데이터 정렬을 사용합니다.
unionWith coll collection인 경우 해당 콜레이션은 무시됩니다.
$unionWith coll이 보기인 경우 해당 컬렉션의 데이터 정렬은 최상위 컬렉션/보기의 데이터 정렬과 일치해야 합니다. 그렇지 않으면 작동 오류가 발생합니다.
MongoDB 검색 지원
MongoDB 6.0 부터는 파이프라인 에서 MongoDB Search $search 또는 $searchMeta 단계를 지정하여 $unionWith Atlas cluster 에서 컬렉션을 검색 수 있습니다. $search 또는 $searchMeta 단계는 $unionWith 파이프라인 내의 첫 번째 단계여야 합니다.
[{ "$unionWith": { "coll": <collection-name>, "pipeline": [{ "$search": { "<operator>": { <operator-specification> } }, ... }] }}][{ "$unionWith": { "coll": <collection-name>, "pipeline": [{ "$searchMeta": { "<collector>": { <collector-specification> } }, ... }] }}]를 $unionWith 사용한 $search 의 예시 보려면 MongoDB Search 튜토리얼 $unionWith를 사용하여 MongoDB Search $ 검색 쿼리 실행하기를 참조하세요.
하위 파이프라인의 네임스페이스
MongoDB 8.0부터 $lookup 및 $unionWith 내의 서브파이프라인의 네임스페이스가 from 및 coll 필드의 올바른 사용을 보장하기 위해 검증됩니다.
$lookup의 경우 지정된 컬렉션이 필요하지 않은 단계를 사용하는 서브파이프라인을 사용할 때는from필드를 생략합니다. 예를 들어$documents단계입니다.마찬가지로,
$unionWith의 경우coll필드를 생략합니다.
변경되지 않은 동작:
예를 들어
$match또는$collStats서브파이프라인과 같이 컬렉션을 위한 단계로 시작하는$lookup의 경우from필드를 포함하고 컬렉션을 지정해야 합니다.마찬가지로
$unionWith의 경우coll필드를 포함하고 컬렉션을 지정합니다.
제한 사항
제한 사항 | 설명 |
|---|---|
집계 파이프라인은 트랜잭션 내에서 | |
$unionWith 파이프라인은 | |
$unionWith 파이프라인은 |
예시
이 페이지의 예시는 sample_mflix 데이터 세트의 데이터를 사용합니다. 이 데이터 세트를 자체 관리형 MongoDB 배포서버에 로드하는 방법에 대한 자세한 내용은 샘플 데이터세트 로드를 참조하세요. 샘플 데이터베이스를 수정한 경우, 이 페이지의 예시를 실행하려면 데이터베이스를 제거하고 다시 생성해야 할 수 있습니다.
영화 데이터의 유니온에서 영화 보고서 만들기
다음 예시에서는 $unionWith 단계를 사용하여 데이터를 결합하고 movies 컬렉션에서 결과를 반환합니다.
보고서 1: 카테고리 및 연도별 모든 영화
다음 집계는 카테고리별로 영화를 나열하는 영화 보고서를 생성합니다. 파이프라인은 $unionWith을(를) 사용하여 movies 컬렉션의 문서를 결합합니다.
db.movies.aggregate( [ { $match: { year: { $lt: 1910 } } }, { $set: { category: "Early Cinema" } }, { $unionWith: { coll: "movies", pipeline: [ { $match: { runtime: { $gt: 1000 } } }, { $set: { category: "Long Runtime" } } ] } }, { $project: { title: 1, year: 1, category: 1, _id: 0 } }, { $sort: { category: 1, year: 1, title: 1 } }] )[ { title: 'The Kiss', year: 1896, category: 'Early Cinema' }, { title: 'The Kiss', year: 1896, category: 'Early Cinema' }, { title: 'The Great Train Robbery', year: 1903, category: 'Early Cinema' }, { title: 'A Corner in Wheat', year: 1909, category: 'Early Cinema' }, { title: 'Centennial', year: 1978, category: 'Long Runtime' }, { title: 'Baseball', year: 1994, category: 'Long Runtime' }]특히 집계 파이프라인은 다음을 사용합니다.
1910이전에 개봉된 영화를 선택하기 위한$match단계입니다.Early Cinema값을 가진category필드를 추가하기 위한$set단계입니다.movies컬렉션의 문서를 결합하는$unionWith단계로,runtime가1000보다 크고Long Runtime카테고리로 태그가 지정된 영화로 필터링됩니다.title,year,category필드만 반환하는$project단계입니다.category,year및title를 기준으로 정렬하는$sort단계.
보고서 2: 장르별 집계 런타임
다음 집계는 장르별 총 런타임을 나열하는 영화 보고서를 만듭니다. 파이프라인은 $unionWith을(를) 사용하여 movies 컬렉션의 문서를 결합합니다.
db.movies.aggregate( [ { $match: { year: { $lt: 1910 } } }, { $unionWith: { coll: "movies", pipeline: [ { $match: { runtime: { $gt: 1000 } } } ] } }, { $group: { _id: "$genres", totalRuntime: { $sum: "$runtime" } } }, { $sort: { totalRuntime: -1 } }] )[ { _id: [ 'Action', 'Adventure', 'Drama' ], totalRuntime: 1256 }, { _id: [ 'Documentary', 'History', 'Sport' ], totalRuntime: 1140 }, { _id: [ 'Short', 'Drama' ], totalRuntime: 14 }, { _id: [ 'Short', 'Western' ], totalRuntime: 11 }, { _id: [ 'Short', 'Romance' ], totalRuntime: 2 }]$match및$unionWith단계는movies컬렉션에서 파이프라인으로 문서를 조회합니다.$sort단계에서는totalRuntime내림차순으로 문서를 정렬합니다.
지정된 문서로 유니온 만들기
$unionWith를 사용하여 pipeline 필드에 지정한 문서와 유니온을 수행할 수 있습니다. pipeline 필드에 $documents 단계를 지정하면 별도의 컬렉션에 저장되지 않은 문서와의 유니온이 수행됩니다.
다음 $unionWith 작업은 pipeline $documents 필드에 지정된 문서와 유니온을 수행합니다.
db.movies.aggregate( [ { $match: { runtime: { $gt: 1000 } } }, { $project: { title: 1, year: 1, _id: 0 } }, { $unionWith: { pipeline: [ { $documents: [ { title: "Movie A", year: 2000 }, { title: "Movie B", year: 2001 } ] } ] } }] )[ { title: 'Centennial', year: 1978 }, { title: 'Baseball', year: 1994 }, { title: 'Movie A', year: 2000 }, { title: 'Movie B', year: 2001 }]이 페이지의 C# 예제에서는 Atlas 샘플 데이터 세트의 sample_mflix 데이터베이스 사용합니다. 무료 MongoDB Atlas cluster 생성하고 샘플 데이터 세트를 로드하는 방법을 학습하려면 MongoDB .NET/ C# 드라이버 문서에서 시작하기 를 참조하세요.
다음 Movie 클래스는 sample_mflix.movies 컬렉션의 문서를 모델링합니다.
[BsonIgnoreExtraElements]public class Movie{ [BsonId] public ObjectId Id { get; set; } [BsonElement("title")] public string Title { get; set; } = null!; [BsonElement("year")] public int? Year { get; set; } [BsonElement("runtime")] public int? Runtime { get; set; } [BsonElement("rated")] public string? Rated { get; set; } [BsonElement("metacritic")] public int Metacritic { get; set; } [BsonElement("plot")] public string? Plot { get; set; } [BsonElement("type")] public string? Type { get; set; } [BsonElement("cast")] public string[]? Cast { get; set; } [BsonElement("directors")] public string[]? Directors { get; set; } [BsonElement("writers")] public string[]? Writers { get; set; } [BsonElement("imdb")] public ImdbData? Imdb { get; set; }}MongoDB .NET/ C# 운전자 사용하여 $unionWith 집계 파이프라인 에 단계를 추가하려면 PipelineDefinition 객체 에서 UnionWith() 메서드를 호출합니다.
다음 예시는 sample_mflix.movies 컬렉션의 Metacritic 점수가 100 인 영화와 동일한 기준을 충족하는 영화를 결합하는 파이프라인 단계를 만듭니다.
var pipeline = new EmptyPipelineDefinition<Movie>() .Match(Builders<Movie>.Filter.Eq(m => m.Metacritic, 100)) .UnionWith( withCollection: _movies, withPipeline: new EmptyPipelineDefinition<Movie>() .Match(Builders<Movie>.Filter.Eq(m => m.Metacritic, 100)));{ "metacritic" : 100, "title" : "Best Kept Secret" }{ "metacritic" : 100, "title" : "Best Kept Secret" }{ "metacritic" : 100, "title" : "Boyhood" }{ "metacritic" : 100, "title" : "Boyhood" }{ "metacritic" : 100, "title" : "Fanny and Alexander" }{ "metacritic" : 100, "title" : "Fanny and Alexander" }{ "metacritic" : 100, "title" : "Lawrence of Arabia" }{ "metacritic" : 100, "title" : "Lawrence of Arabia" }{ "metacritic" : 100, "title" : "The Conformist" }{ "metacritic" : 100, "title" : "The Conformist" }{ "metacritic" : 100, "title" : "The Godfather" }{ "metacritic" : 100, "title" : "The Godfather" }{ "metacritic" : 100, "title" : "The Leopard" }{ "metacritic" : 100, "title" : "The Leopard" }{ "metacritic" : 100, "title" : "The Wizard of Oz" }{ "metacritic" : 100, "title" : "The Wizard of Oz" }이 페이지의 Node.js 예제에서는 Atlas 샘플 데이터 세트의 sample_mflix 데이터베이스 사용합니다. 무료 MongoDB Atlas cluster 생성하고 샘플 데이터 세트를 로드하는 방법을 학습하려면 MongoDB Node.js 운전자 설명서에서 시작하기 를 참조하세요.
MongoDB Node.js 운전자 사용하여 집계 파이프라인 에 $unionWith 단계를 추가하려면 파이프라인 객체 에서 $unionWith 연산자 사용합니다.
다음 예시 sample_mflix.movies 컬렉션 에서 수신 문서를 sample_mflix.movies 컬렉션 의 movie 문서와 결합하는 파이프라인 단계를 만듭니다. 그런 다음 이 예시 에서는 집계 파이프라인 실행합니다.
const db = client.db("sample_mflix");const collection = db.collection("movies");
const pipeline = [{ $unionWith: { coll: "Movies" } }];
const cursor = collection.aggregate(pipeline);return cursor;