Docs Menu
Docs Home
/ /

$merge (aggregation stage)

Note

This page describes the $merge stage, which outputs the aggregation pipeline results to a collection. For the $mergeObjects operator, which merges documents into a single document, see $mergeObjects.

$merge

Writes the results of the aggregation pipeline to a specified collection. The $merge operator must be the last stage in the pipeline.

The $merge stage:

  • Can output to a collection in the same or different database.

  • Can output to the same collection that is being aggregated. For more information, see Output to the Same Collection that is Being Aggregated.

  • Consider the following points when using $merge or $out stages in an aggregation pipeline:

    • Starting in MongoDB 5.0, pipelines with a $merge stage can run on replica set secondary nodes if all the nodes in the cluster have the featureCompatibilityVersion set to 5.0 or higher and the read preference allows secondary reads.

      • $merge and $out stages run on secondary nodes, but write operations are sent to the primary node.

      • Not all driver versions support $merge operations sent to the secondary nodes. For details, see the driver documentation.

    • In earlier MongoDB versions, pipelines with $out or $merge stages always run on the primary node and read preference isn't considered.

  • Creates a new collection if the output collection does not already exist.

  • Can incorporate results (insert new documents, merge documents, replace documents, keep existing documents, fail the operation, process documents with a custom update pipeline) into an existing collection.

  • Can output to a sharded collection. Input collection can also be sharded.

For a comparison with the $out stage which also outputs the aggregation results to a collection, see $merge and $out Comparison.

Note

On-Demand Materialized Views

$merge can incorporate the pipeline results into an existing output collection rather than perform a full replacement of the collection. This functionality allows users to create on-demand materialized views, where the content of the output collection is incrementally updated when the pipeline is run.

For more information on this use case, see On-Demand Materialized Views as well as the examples on this page.

Materialized views are separate from read-only views. For information on creating read-only views, see read-only views.

You can use $merge for deployments hosted in the following environments:

  • MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud

$merge has the following syntax:

{ $merge: {
into: <collection> -or- { db: <db>, coll: <collection> },
on: <identifier field> -or- [ <identifier field1>, ...], // Optional
let: <variables>, // Optional
whenMatched: <replace|keepExisting|merge|fail|pipeline>, // Optional
whenNotMatched: <insert|discard|fail> // Optional
} }

For example:

{ $merge: { into: "myOutput", on: "_id", whenMatched: "replace", whenNotMatched: "insert" } }

If using all default options for $merge, including writing to a collection in the same database, you can use the simplified form:

{ $merge: <collection> } // Output collection is in the same database

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

Field
Description

The output collection. Specify either:

  • The collection name as a string to output to a collection in the same database where the aggregation is run. For example:

    into: "myOutput"

  • The database and collection name in a document to output to a collection in the specified database. For example:

    into: { db:"myDB", coll:"myOutput" }

If the output collection does not exist, $merge creates the collection:

  • For a replica set or a standalone, if the output database does not exist, $merge also creates the database.

  • For a sharded cluster, the specified output database must already exist.

The output collection can be a sharded collection.

Optional. Field or fields that act as a unique identifier for a document. The identifier determines if a results document matches an existing document in the output collection. Specify either:

  • A single field name as a string. For example:

    on: "_id"

  • A combination of fields in an array. For example:

    on: [ "date", "customerId" ]
    The order of the fields in the array does not matter, and you cannot specify the same field multiple times.

For the specified field or fields:

  • The aggregation results documents must contain the field(s) specified in the on, unless the on field is the _id field. If the _id field is missing from a results document, MongoDB adds it automatically.

  • For deployments running MongoDB 8.0 and earlier, specified field or fields for on cannot be missing or contain a null value. Starting in MongoDB 8.1, if the supporting index is not sparse, the specified field or fields for on can be missing or contain a null value.

  • The specified field or fields cannot contain an array value.

$merge requires a unique index with keys that correspond to the on identifier fields. Although the order of the index key specification does not matter, the unique index must only contain the on fields as its keys.

  • The index must also have the same collation as the aggregation's collation.

  • The unique index can be a sparse index.

  • The unique index cannot be a partial index.

  • For output collections that already exist, the corresponding index must already exist.

The default value for on depends on the output collection:

  • If the output collection does not exist, the on identifier must be and defaults to the _id field. The corresponding unique _id index is automatically created.

    • To use a different on identifier field(s) for a collection that does not exist, you can create the collection first by creating a unique index on the desired field(s). See the section on non-existent output collection for an example.

    • Starting in MongoDB 8.3, the server checks to ensure that the automatically created _id index matches the query's collation. If the collations do not match, the _id index cannot provide uniqueness for the query, and the query will not run.

  • If the existing output collection is unsharded, the on identifier defaults to the _id field.

  • If the existing output collection is a sharded collection, the on identifier defaults to all the shard key fields and the _id field. If specifying a different on identifier, the on must contain all the shard key fields.

Optional. The behavior of $merge if a result document and an existing document in the collection have the same value for the specified on field(s).

You can specify either:

  • One of the pre-defined action strings:

    Action
    Description

    Replace the existing document in the output collection with the matching results document.

    When performing a replace, the replacement document cannot result in a modification of the _id value or, if the output collection is sharded, the shard key value. Otherwise, the operation generates an error.

    To avoid this error, if the on field does not include the _id field, remove the _id field in the aggregation results to avoid the error, such as with a preceding $unset stage, and so on.

    Keep the existing document in the output collection.

    "merge" (Default)

    Merge the matching documents (similar to the $mergeObjects operator).

    • If the results document contains fields not in the existing document, add these new fields to the existing document.

    • If the results document contains fields in the existing document, replace the existing field values with those from the results document.

    For example, if the output collection has the document:

    { _id: 1, a: 1, b: 1 }

    And the aggregation results has the document:

    { _id: 1, b: 5, z: 1 }

    Then, the merged document is:

    { _id: 1, a: 1, b: 5, z: 1 }

    When performing a merge, the merged document cannot result in a modification of the _id value or, if the output collection is sharded, the shard key value. Otherwise, the operation generates an error.

    To avoid this error, if the on field does not include the _id field, remove the _id field in the aggregation results to avoid the error, such as with a preceding $unset stage, and so on.

    Stop and fail the aggregation operation. Any changes to the output collection from previous documents are not reverted.

  • An aggregation pipeline to update the document in the collection.

    [ <stage1>, <stage2> ... ]

    The pipeline can only consist of the following stages:

    The pipeline cannot modify the on field's value. For example, if you are matching on the field month, the pipeline cannot modify the month field.

    The whenMatched pipeline can directly access the fields of the existing documents in the output collection using $<field>.

    To access the fields from the aggregation results documents, use either:

    • The built-in $$new variable to access the field. Specifically, $$new.<field>. The $$new variable is only available if the let specification is omitted.

    • The user-defined variables in the let field.

      Specify the double dollar sign ($$) prefix together with the variable name in the form $$<variable_name>. For example, $$year. If the variable is set to a document, you can also include a document field in the form $$<variable_name>.<field>. For example, $$year.month.

      For more examples, see Use Variables to Customize the Merge.

Optional. Specifies variables for use in the whenMatched pipeline.

Specify a document with the variable names and value expressions:

{ <variable_name_1>: <expression_1>,
...,
<variable_name_n>: <expression_n> }

If unspecified, defaults to { new: "$$ROOT" } (see ROOT). The whenMatched pipeline can access the $$new variable.

To access the variables in the whenMatched pipeline:

Specify the double dollar sign ($$) prefix together with the variable name in the form $$<variable_name>. For example, $$year. If the variable is set to a document, you can also include a document field in the form $$<variable_name>.<field>. For example, $$year.month.

For examples, see Use Variables to Customize the Merge.

Optional. The behavior of $merge if a result document does not match an existing document in the out collection.

You can specify one of the pre-defined action strings:

Action
Description

"insert" (Default)

Insert the document into the output collection.

Discard the document. Specifically, $merge does not insert the document into the output collection.

Stop and fail the aggregation operation. Any changes already written to the output collection are not reverted.

If the _id field is not present in a document from the aggregation pipeline results, the $merge stage generates it automatically.

For example, in the following aggregation pipeline, $project excludes the _id field from the documents passed into $merge. When $merge writes these documents to the "newCollection", $merge generates a new _id field and value.

db.movies.aggregate( [
{ $project: { _id: 0 } },
{ $merge : { into : "newCollection" } }
] )

The $merge operation creates a new collection if the specified output collection does not exist.

  • The output collection is created when $merge writes the first document into the collection and is immediately visible.

  • If the aggregation fails, any writes completed by the $merge before the error will not be rolled back.

Note

For a replica set or a standalone, if the output database does not exist, $merge also creates the database.

For a sharded cluster, the specified output database must already exist.

If the output collection does not exist, $merge requires the on identifier to be the _id field. To use a different on field value for a collection that does not exist, you can create the collection first by creating a unique index on the desired field(s) first. For example, if the output collection newDailyCommentCount does not exist and you want to specify the commentDate field as the on identifier:

db.newDailyCommentCount.createIndex(
{ commentDate: 1 }, { unique: true } )
db.comments.aggregate( [
{ $match: { date: { $gte: new Date("2002-01-01"),
$lt: new Date("2002-02-01") } } },
{ $group: { _id: { $dateToString: { format: "%Y-%m-%d",
date: "$date" } }, count: { $sum: 1 } } },
{ $project: { _id: 0, commentDate: { $toDate: "$_id" },
count: 1 } },
{ $merge : { into : "newDailyCommentCount",
on: "commentDate" } }
] )

The $merge stage can output to a sharded collection. When the output collection is sharded, $merge uses the _id field and all the shard key fields as the default on identifier. If you override the default, the on identifier must include all the shard key fields:

{ $merge: {
into: "<shardedColl>" or { db:"<sharding enabled db>", coll: "<shardedColl>" },
on: [ "<shardkeyfield1>", "<shardkeyfield2>",... ], // Shard key fields and any additional fields
let: <variables>, // Optional
whenMatched: <replace|keepExisting|merge|fail|pipeline>, // Optional
whenNotMatched: <insert|discard|fail> // Optional
} }

For example, use the sh.shardCollection() method to create a new sharded collection moviesByYearAndRating with the rated field as the shard key.

sh.shardCollection(
"sample_mflix.moviesByYearAndRating", // Namespace of the collection to shard
{ rated: 1 }, // Shard key
);

The moviesByYearAndRating collection will contain documents with movie statistics by year (year field) and content rating (shard key); specifically, the on identifier is ["year", "rated"] (the ordering of the fields does not matter). Because $merge requires a unique index with keys that correspond to the on identifier fields, create the unique index (the ordering of the fields do not matter): [1]

db.moviesByYearAndRating.createIndex(
{ rated: 1, year: 1 }, { unique: true } )

With the sharded collection moviesByYearAndRating and the unique index created, you can use $merge to output the aggregation results to this collection, matching on [ "year", "rated" ] as in this example:

db.movies.aggregate( [
{ $match: { rated: { $ne: null }, year: { $ne: null } } },
{ $group: {
_id: { year: "$year", rated: "$rated" },
movieCount: { $sum: 1 } } },
{ $project: { _id: 0, year: "$_id.year", rated: "$_id.rated",
movieCount: 1 } },
{ $merge: { into: "moviesByYearAndRating",
"on": [ "year", "rated" ], whenMatched: "replace",
whenNotMatched: "insert" } }
] )
[1] The sh.shardCollection() method can also create a unique index on the shard key when passed the { unique: true } option if: the shard key is range-based, the collection is empty, and a unique index on the shard key doesn't already exist.In the previous example, because the on identifier is the shard key and another field, a separate operation to create the corresponding index is required.

$merge can replace an existing document in the output collection if the aggregation results contain a document or documents that match based on the on specification. As such, $merge can replace all documents in the existing collection if the aggregation results include matching documents for all existing documents in the collection and you specify "replace" for whenMatched.

However, to replace an existing collection regardless of the aggregation results, use $out instead.

The $merge errors if the $merge results in a change to an existing document's _id value.

Tip

To avoid this error, if the on field does not include the _id field, remove the _id field in the aggregation results to avoid the error, such as with a preceding $unset stage, and so on.

Additionally, for a sharded collection, $merge also generates an error if it results in a change to the shard key value of an existing document.

Any writes completed by the $merge before the error will not be rolled back.

If the unique index used by $merge for on field(s) is dropped mid-aggregation, there is no guarantee that the aggregation will be killed. If the aggregation continues, there is no guarantee that documents do not have duplicate on field values.

If the $merge attempts to write a document that violates any unique index on the output collection, the operation generates an error. For example:

  • Insert a non-matching document that violates a unique index other than the index on the on field(s).

  • Fail if there is a matching document in the collection. Specifically, the operation attempts to insert the matching document which violates the unique index on the on field(s).

  • Replace an existing document with a new document that violates a unique index other than the index on the on field(s).

  • Merge the matching documents that results in a document that violates a unique index other than the index on the on field(s).

If your collection uses schema validation and has validationAction set to error, inserting an invalid document or updating a document with invalid values with $merge throws a MongoServerError and the document is not written to the target collection. If there are multiple invalid documents, only the first invalid document encountered throws an error. All valid documents are written to the target collection, and all invalid documents fail to write.

$merge inserts the document directly into the output collection when all of the following are true:

  • The value of whenMatched is an aggregation pipeline.

  • The value of whenNotMatched is insert.

  • There is no match for a document in the output collection.

With the introduction of $merge, MongoDB provides two stages, $merge and $out, for writing the results of the aggregation pipeline to a collection:

$merge
  • Can output to a collection in the same or different database.

  • Can output to a collection in the same or different database.

  • Creates a new collection if the output collection does not already exist.

  • Creates a new collection if the output collection does not already exist.

  • Replaces the output collection completely if it already exists.

  • Can output to a sharded collection. Input collection can also be sharded.

  • Cannot output to a sharded collection. Input collection, however, can be sharded.

  • Corresponds to SQL statements:

    • MERGE.

    • INSERT INTO T2 SELECT FROM T1.

    • SELECT INTO T2 FROM T1.

    • Create/Refresh Materialized Views.

  • Corresponds to SQL statement:

    • INSERT INTO T2 SELECT FROM T1.

    • SELECT INTO T2 FROM T1.

Warning

When $merge outputs to the same collection that is being aggregated, documents may get updated multiple times or the operation may result in an infinite loop. This behavior occurs when the update performed by $merge changes the physical location of documents stored on disk. When the physical location of a document changes, $merge may view it as an entirely new document, resulting in additional updates. For more information on this behavior, see Halloween Problem.

$merge can output to the same collection that is being aggregated. You can also output to a collection which appears in other stages of the pipeline, such as $lookup.

Restrictions
Description

An aggregation pipeline cannot use $merge inside a transaction.

An aggregation pipeline cannot use $merge to output to a time series collection.

Separate from materialized view

A view definition cannot include the $merge stage. If the view definition includes nested pipeline (for example, the view definition includes $facet stage), this $merge stage restriction applies to the nested pipelines as well.

$lookup stage

$lookup stage's nested pipeline cannot include the $merge stage.

$facet stage

$facet stage's nested pipeline cannot include the $merge stage.

$unionWith stage's nested pipeline cannot include the $merge stage.

"linearizable" read concern

The $merge stage cannot be used in conjunction with read concern "linearizable". That is, if you specify "linearizable" read concern for db.collection.aggregate(), you cannot include the $merge stage in the pipeline.

Back

$match

On this page