> This page location: /docs.md > /docs/development.md > /docs/manual/reference/mql.md > /docs/manual/reference/mql/aggregation-stages.md

> For the complete MongoDB documentation index, see www.mongodb.com/docs/llms.txt

<!--
Tab options on this page. Append to the .md URL to filter:
  ?tabs=<id,...>   select specific tabs (e.g. ?tabs=nodejs,shell)
  ?allTabs=true    include every tab
  (no param)       default: one tab per tabset

Available tabs:
  other tabs: search, searchmeta
  drivers: shell, csharp, nodejs
-->

# $unionWith (aggregation stage)

## Definition

**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.

## Syntax

The `$unionWith` stage has the following syntax:

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

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

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

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

| Field | Necessity | Description |
| --- | --- | --- |
| [coll](https://www.mongodb.com/docs/manual/reference/operator/aggregation/unionwith.md#std-label-unionWith-coll) | Required if `pipeline` is omitted. Otherwise optional. | The collection or view whose [pipeline](https://www.mongodb.com/docs/manual/reference/operator/aggregation/unionwith.md#std-label-unionWith-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`.](https://www.mongodb.com/docs/manual/reference/operator/aggregation/documents.md#mongodb-pipeline-pipe.-documents) |
| [pipeline](https://www.mongodb.com/docs/manual/reference/operator/aggregation/unionwith.md#std-label-unionWith-pipeline) | 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.](https://www.mongodb.com/docs/manual/reference/operator/aggregation/unionwith.md#std-label-unionWith-example-specified-docs) The pipeline cannot include the [`$out`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/out.md#mongodb-pipeline-pipe.-out) and [`$merge`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/merge.md#mongodb-pipeline-pipe.-merge) stages. Starting in v6.0, the `pipeline` can contain the [MongoDB Search](https://www.mongodb.com/docs/atlas/atlas-search/) [`$search`](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search) stage as the first stage inside the pipeline. To learn more, see [MongoDB Search Support.](https://www.mongodb.com/docs/manual/reference/operator/aggregation/unionwith.md#std-label-fts-unionwith-behavior) |

The [`$unionWith`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/unionwith.md#mongodb-pipeline-pipe.-unionWith) operation would correspond to the following SQL statement:

```sql
SELECT *
FROM Collection1
WHERE ...
UNION ALL
SELECT *
FROM Collection2
WHERE ...
```

## Considerations

### Duplicate Results

The combined results from the previous stage and the [`$unionWith`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/unionwith.md#mongodb-pipeline-pipe.-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:

```javascript
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 } }
   ] } }
] )

```

**Output:**

```javascript
[
  { title: 'Centennial' },
  { title: 'Baseball' },
  { title: 'Centennial' },
  { title: 'Baseball' }
]

```

To remove the duplicates, you can include a [`$group`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/group.md#mongodb-pipeline-pipe.-group) stage to group by the `title` field. The result set no longer contains duplicates:

```javascript
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 } }
] )

```

**Output:**

```javascript
[
  { _id: 'Baseball' },
  { _id: 'Centennial' }
]

```

### Collation

If the [`db.collection.aggregate()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.aggregate.md#mongodb-method-db.collection.aggregate) includes a `collation` document, the operation uses that collation and ignores any other collations.

If the [`db.collection.aggregate()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.aggregate.md#mongodb-method-db.collection.aggregate) does not include a `collation` document, the [`db.collection.aggregate()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.aggregate.md#mongodb-method-db.collection.aggregate) method uses the collation for the top-level collection/view on which the [`db.collection.aggregate()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.aggregate.md#mongodb-method-db.collection.aggregate) is run:

- If the [$unionWith coll](https://www.mongodb.com/docs/manual/reference/operator/aggregation/unionwith.md#std-label-unionWith-coll) is a collection, its collation is ignored.

- If the [$unionWith coll](https://www.mongodb.com/docs/manual/reference/operator/aggregation/unionwith.md#std-label-unionWith-coll) is a [view](https://www.mongodb.com/docs/manual/core/views.md#std-label-views-landing-page), then its collation must match that of the top-level collection/view. Otherwise, the operation errors.

### MongoDB Search Support

Starting in MongoDB 6.0, you can specify the [MongoDB Search](https://www.mongodb.com/docs/atlas/atlas-search/) [`$search`](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search) or [`$searchMeta`](https://www.mongodb.com/docs/search/query/aggregation-stages/searchMeta.md#mongodb-pipeline-pipe.-searchMeta) stage in the `$unionWith` pipeline to search collections on the Atlas cluster. The [`$search`](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search) or the [`$searchMeta`](https://www.mongodb.com/docs/search/query/aggregation-stages/searchMeta.md#mongodb-pipeline-pipe.-searchMeta) stage must be the first stage inside the `$unionWith` pipeline.

### $search

```text
[{
  "$unionWith": {
    "coll": <collection-name>,
    "pipeline": [{
      "$search": {
        "<operator>": {
          <operator-specification>
        }
      },
      ...
    }]
  }
}]
```

To see an example of [`$unionWith`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/unionwith.md#mongodb-pipeline-pipe.-unionWith) with [`$search`](https://www.mongodb.com/docs/search/query/aggregation-stages/search.md#mongodb-pipeline-pipe.-search), see the MongoDB Search tutorial [Run a MongoDB Search $search Query Using $unionWith.](https://www.mongodb.com/docs/atlas/atlas-search/tutorial/search-with-unionwith/)

### Namespaces in Subpipelines

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`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/documents.md#mongodb-pipeline-pipe.-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`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/match.md#mongodb-pipeline-pipe.-match) or [`$collStats`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/collstats.md#mongodb-pipeline-pipe.-collStats) subpipeline, you must include the `from` field and specify the collection.

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

### Restrictions

| Restrictions | Description |
| --- | --- |
| [transactions](https://www.mongodb.com/docs/manual/core/transactions.md#std-label-transactions) | An aggregation pipeline cannot use [`$unionWith`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/unionwith.md#mongodb-pipeline-pipe.-unionWith) inside [transactions.](https://www.mongodb.com/docs/manual/core/transactions.md#std-label-transactions) |
| [`$out`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/out.md#mongodb-pipeline-pipe.-out) | The [$unionWith pipeline](https://www.mongodb.com/docs/manual/reference/operator/aggregation/unionwith.md#std-label-unionWith-pipeline) cannot include the [`$out`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/out.md#mongodb-pipeline-pipe.-out) stage. |
| [`$merge`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/merge.md#mongodb-pipeline-pipe.-merge) | The [$unionWith pipeline](https://www.mongodb.com/docs/manual/reference/operator/aggregation/unionwith.md#std-label-unionWith-pipeline) cannot include the [`$merge`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/merge.md#mongodb-pipeline-pipe.-merge) stage. |

## Examples

### MongoDB Shell

The examples on this page use data from the [sample\_mflix dataset](https://www.mongodb.com/docs/manual/sample-data/sample-mflix.md#std-label-sample-mflix). For details on how to load this dataset into your self-managed MongoDB deployment, see [Load the Sample Dataset](https://www.mongodb.com/docs/manual/sample-data/load-sample-data-local.md#std-label-sample-dataset-local). 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.

### Create Movie Reports from the Union of Movie Data

The following examples use the [`$unionWith`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/unionwith.md#mongodb-pipeline-pipe.-unionWith) stage to combine data and return results from the `movies` collection.

### Report 1: All Movies by Category and Year

The following aggregation creates a movie report that lists movies by category. The pipeline uses [`$unionWith`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/unionwith.md#mongodb-pipeline-pipe.-unionWith) to combine documents from the `movies` collection:

```javascript
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 } }
] )

```

**Output:**

```javascript
[
  { 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`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/match.md#mongodb-pipeline-pipe.-match) stage to select movies released before `1910`.

- A [`$set`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/set.md#mongodb-pipeline-pipe.-set) stage to add a `category` field with the value `Early Cinema`.

- A [`$unionWith`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/unionwith.md#mongodb-pipeline-pipe.-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`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project) stage to return only the `title`, `year`, and `category` fields.

- A [`$sort`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sort.md#mongodb-pipeline-pipe.-sort) stage to sort by the `category`, the `year`, and the `title`.

### Report 2: Aggregated Runtime by Genre

The following aggregation creates a movie report that lists the total runtime per genre. The pipeline uses [`$unionWith`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/unionwith.md#mongodb-pipeline-pipe.-unionWith) to combine documents from the `movies` collection:

```javascript
db.movies.aggregate( [
   { $match: { year: { $lt: 1910 } } },
   { $unionWith: { coll: "movies", pipeline: [
      { $match: { runtime: { $gt: 1000 } } }
   ] } },
   { $group: { _id: "$genres", totalRuntime: { $sum: "$runtime" } } },
   { $sort: { totalRuntime: -1 } }
] )

```

**Output:**

```javascript
[
  { _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`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/match.md#mongodb-pipeline-pipe.-match) and [`$unionWith`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/unionwith.md#mongodb-pipeline-pipe.-unionWith) stages retrieve documents from the `movies` collection into the pipeline.

- The [`$group`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/group.md#mongodb-pipeline-pipe.-group) stage groups by the `genres` field and uses [`$sum`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sum.md#mongodb-group-grp.-sum) to calculate the total `runtime` per `genres` value.

- The [`$sort`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/sort.md#mongodb-pipeline-pipe.-sort) stage orders the documents by descending `totalRuntime`.

### Create a Union with Specified Documents

You can use `$unionWith` to perform a union with documents that you specify in the `pipeline` field. When you specify a [`$documents`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/documents.md#mongodb-pipeline-pipe.-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`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/documents.md#mongodb-pipeline-pipe.-documents) field:

```javascript
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 }
               ]
            }
         ]
      }
   }
] )

```

**Output:**

```javascript
[
  { title: 'Centennial', year: 1978 },
  { title: 'Baseball', year: 1994 },
  { title: 'Movie A', year: 2000 },
  { title: 'Movie B', year: 2001 }
]

```
