$merge

The `$merge` stage in an aggregation pipeline is used to write the results of the aggregation query into a specified collection. This stage combines data transformation and data persistence in a single operation.

Syntax

{
  $merge: {
    into: <collection>,
    on: <field or fields>,
    whenMatched: <action>,
    whenNotMatched: <action>
  }
}

Parameters

intostringrequired

Specifies the target collection where the aggregation results will be written.

onstring

Specifies the field(s) to identify matching documents in the target collection.

whenMatchedstring

Action when a matching document is found. Options: merge, replace, keepExisting, fail, or a custom pipeline.

whenNotMatchedstring

Action when no matching document is found. Options: insert or discard.

Examples

Sample Data

{
  "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
  "name": "Lakeshore Retail | DJ Equipment Stop",
  "sales": {
    "salesByCategory": [
      { "categoryName": "DJ Headphones", "totalSales": 35921 }
    ]
  }
}

Merge data into a collection

Aggregate documents and write results to salesSummary, updating existing documents or inserting new ones.

This query groups by category and merges results into a summary collection.

Query:

db.sales.aggregate([
  {
    $group: {
      _id: "$sales.salesByCategory.categoryName",
      totalSales: { $sum: "$sales.salesByCategory.totalSales" }
    }
  },
  {
    $merge: {
      into: "salesSummary",
      on: "_id",
      whenMatched: "merge",
      whenNotMatched: "insert"
    }
  }
])

Output:

Documents merged into 'salesSummary' collection.

Replace documents in the target collection

Replace documents in the promotionEventsSummary collection based on the _id field.

This query projects event data and replaces matching documents in target collection.

Query:

db.promotionEvents.aggregate([
  {
    $project: {
      _id: "$eventName",
      startDate: "$promotionalDates.startDate",
      totalDiscounts: { $size: "$discounts" }
    }
  },
  {
    $merge: {
      into: "promotionEventsSummary",
      on: "_id",
      whenMatched: "replace",
      whenNotMatched: "insert"
    }
  }
])

Output:

Documents replaced in 'promotionEventsSummary' collection.

Related