For AI agents: a documentation index is available at https://www.mongodb.com/ko-kr/docs/llms.txt — markdown versions of all pages are available by appending .md to any URL path.

$unionWith (aggregation stage)

$unionWith

Changed in version 8.0.

Combines two aggregations into a single result set. $unionWith outputs the combined result set (including duplicates) to the next stage.

The order in which the combined result set documents are output is unspecified.

The $unionWith stage has the following syntax:

{ $unionWith: { coll: "<collection>", pipeline: [ <stage1>, ... ] } }

To include all documents from the specified collection without any processing, you can use the simplified form:

{ $unionWith: "<collection>" } // Include all documents from the specified collection

The $unionWith stage takes a document with the following fields:

Field
Necessity
Description

Required if pipeline is omitted. Otherwise optional.

The collection or view whose pipeline results you want to include in the result set.

If you omit the coll field, you must specify a pipeline field with a first stage of $documents.

Required if coll is omitted. Otherwise optional.

An aggregation pipeline to apply to the input documents.

  • If you specify coll, the pipeline applies to the documents in coll.

  • If you omit coll, the pipeline applies to the documents in the pipeline's $documents stage. For an example, see Create a Union with Specified Documents.

The pipeline cannot include the $out and $merge stages. Starting in v6.0, the pipeline can contain the MongoDB Search $search stage as the first stage inside the pipeline. To learn more, see MongoDB Search Support.

The $unionWith operation would correspond to the following SQL statement:

SELECT *FROM Collection1WHERE ...UNION ALLSELECT *FROM Collection2WHERE ...

The combined results from the previous stage and the $unionWith stage can include duplicates.

For example, the following aggregation combines the title field projection results from two queries on the movies collection. The result set contains duplicates:

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' }]

To remove the duplicates, you can include a $group stage to group by the title field. The result set no longer contains duplicates:

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' }]

If the db.collection.aggregate() includes a collation document, the operation uses that collation and ignores any other collations.

If the db.collection.aggregate() does not include a collation document, the db.collection.aggregate() method uses the collation for the top-level collection/view on which the db.collection.aggregate() is run:

  • If the $unionWith coll is a collection, its collation is ignored.

  • If the $unionWith coll is a view, then its collation must match that of the top-level collection/view. Otherwise, the operation errors.

Starting in MongoDB 6.0, you can specify the MongoDB Search $search or $searchMeta stage in the $unionWith pipeline to search collections on the Atlas cluster. The $search or the $searchMeta stage must be the first stage inside the $unionWith pipeline.

To see an example of $unionWith with $search, see the MongoDB Search tutorial Run a MongoDB Search $search Query Using $unionWith.

Starting in MongoDB 8.0, namespaces in subpipelines within $lookup and $unionWith are validated to ensure the correct use of from and coll fields:

  • For $lookup, omit the from field if you use a subpipeline with a stage which doesn't require a specified collection. For example, a $documents stage.

  • Similarly, for $unionWith, omit the coll field.

Unchanged behavior:

  • For a $lookup that starts with a stage for a collection, for example a $match or $collStats subpipeline, you must include the from field and specify the collection.

  • Similarly, for $unionWith, include the coll field and specify the collection.

Restrictions
Description

An aggregation pipeline cannot use $unionWith inside transactions.

The $unionWith pipeline cannot include the $out stage.

The $unionWith pipeline cannot include the $merge stage.

The examples on this page use data from the sample_mflix dataset. For details on how to load this dataset into your self-managed MongoDB deployment, see Load the Sample Dataset. If you made any modifications to the sample databases, you may need to drop and recreate the databases to run the examples on this page.

The following examples use the $unionWith stage to combine data and return results from the movies collection.

The following aggregation creates a movie report that lists movies by category. The pipeline uses $unionWith to combine documents from the movies collection:

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' }]

Specifically, the aggregation pipeline uses:

  • A $match stage to select movies released before 1910.

  • A $set stage to add a category field with the value Early Cinema.

  • A $unionWith stage to combine documents from the movies collection, filtered to movies with a runtime greater than 1000 and tagged with the Long Runtime category.

  • A $project stage to return only the title, year, and category fields.

  • A $sort stage to sort by the category, the year, and the title.

The following aggregation creates a movie report that lists the total runtime per genre. The pipeline uses $unionWith to combine documents from the movies collection:

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 }]
  • The $match and $unionWith stages retrieve documents from the movies collection into the pipeline.

  • The $group stage groups by the genres field and uses $sum to calculate the total runtime per genres value.

  • The $sort stage orders the documents by descending totalRuntime.

You can use $unionWith to perform a union with documents that you specify in the pipeline field. When you specify a $documents stage in the pipeline field, you perform a union with documents that aren't stored in a separate collection.

The following $unionWith operation performs a union with documents specified in the pipeline $documents field:

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 }]