定義
構文
$unionWith ステージの構文は次のとおりです。
{ $unionWith: { coll: "<collection>", pipeline: [ <stage1>, ... ] } }指定したコレクションの全ドキュメントを処理せずに含めるには、簡略化された形式を使用できます。
{ $unionWith: "<collection>" } // Include all documents from the specified collection$unionWithステージは、次のフィールドを持つドキュメントを取得します。
フィールド | 必要性 | 説明 |
|---|---|---|
| ||
| 入力ドキュメントに適用する集計パイプライン。
パイプラインには |
$unionWith操作は、次の SQL ステートメントに対応します。
SELECT *FROM Collection1WHERE ...UNION ALLSELECT *FROM Collection2WHERE ...Considerations
重複した結果
前のステージと $unionWith ステージから組み合わせた結果には重複が含まれる場合があります。
例、次の集計は、moviesコレクションに対する 2 つのクエリからの 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 がコレクションの場合、その照合は無視されます。
$unionWith coll がビューの場合、その照合は最上位のコレクションやビューの照合と一致する必要があります。そうでない場合はエラーとなります。
Atlas Search サポート
MongoDB 6.0 以降では、 $unionWith パイプラインで Atlas Search $search または $searchMeta ステージを指定して、Atlas クラスター上のコレクションを検索できます。$search または $searchMeta ステージは、 $unionWith パイプライン内の最初のステージである必要があります。
[{ "$unionWith": { "coll": <collection-name>, "pipeline": [{ "$search": { "<operator>": { <operator-specification> } }, ... }] }}][{ "$unionWith": { "coll": <collection-name>, "pipeline": [{ "$searchMeta": { "<collector>": { <collector-specification> } }, ... }] }}]$unionWithとともに$search を使用した例については、Atlas Search チュートリアルの「 $unionWith を使用して Atlas Search $search クエリを実行する 」を参照してください。
制限事項
制限事項 | 説明 |
|---|---|
集計パイプラインでは、 トランザクション | |
$unionWith パイプラインには | |
$unionWith パイプラインには |
例
このページの例では、sample_mflix データセット のデータを使用しています。自己管理型 MongoDB 配置にこのデータセットをロードする方法の詳細については、「サンプル データセットのロード」を参照してください。サンプル データベースに何らかの変更を加えた場合は、今ページの例を実行するには、データベースを削除して再作成する必要がある可能性があります。
映画データのUnionから映画レポートを作成
次の例では、$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' }]具体的には、集計パイプラインでは次のものが使用されます。
$matchより前にリリースされた映画を選択するための ステージ1910値
$setを持つ フィールドを追加するcategoryEarly Cinemaステージ。$unionWithmoviesコレクションのドキュメントを結合するためのruntime1000Long Runtimeステージは、 が より大きい映画にフィルタリングし、 カテゴリでタグ付けされます。、 、
$projectフィールドのみを返す ステージ。titleyearcategory$sortcategoryyear、 、 で並べ替えるtitleステージ。
レポート 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の降順で並べ替えます。
指定されたドキュメントとの Union の作成
$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クラスターを無料で作成して、サンプルデータセットをロードする方法については、 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;