$replaceWith

The `$replaceWith` aggregation stage operator is used to replace the input document with the specified document. It transforms documents from one structure to another or replaces them entirely with new fields and values.

Syntax

{
  $replaceWith: <newDocument>
}

Parameters

newDocumentobjectrequired

The new document to replace the original document.

Examples

Sample Data

{
  "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4",
  "name": "First Up Consultants | Beverage Shop",
  "sales": {
    "totalSales": 75670,
    "salesByCategory": [
      { "categoryName": "Wine Accessories", "totalSales": 34440 }
    ]
  }
}

Replace document with subset of fields

Match a specific document and replace its contents with a subset of fields.

This query transforms the document structure by replacing it with selected fields.

Query:

db.stores.aggregate([
  {
    $match: {
      "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4"
    }
  },
  {
    $replaceWith: {
      storeName: "$name",
      totalSales: "$sales.totalSales"
    }
  }
])

Output:

[
  {
    "storeName": "First Up Consultants | Beverage Shop",
    "totalSales": 75670
  }
]

Replace with nested field

Replace the entire document with a nested field from the original.

This query promotes a nested field to become the entire document.

Query:

db.stores.aggregate([
  {
    $replaceWith: "$sales"
  }
])

Output:

[
  {
    "totalSales": 75670,
    "salesByCategory": [
      { "categoryName": "Wine Accessories", "totalSales": 34440 }
    ]
  }
]

Related