Skip to content

$replaceWith

The $replaceWith stage is an alias for $replaceRoot but supports any expression, not just a field path.


📌 Syntax

{ "$replaceWith": <expression> }

✅ Base Example – Replace With Embedded Customer

{ "$replaceWith": "$customer" }

🧱 Deep Nested Example – Merge Order ID with Customer Info

📌 Stage

{
  "$replaceWith": {
    "$mergeObjects": ["$customer", { "orderId": "$orderId" }]
  }
}

📥 Input

{
  "orderId": 55,
  "customer": {
    "name": "Bob",
    "email": "bob@example.com"
  }
}

📤 Output

{
  "name": "Bob",
  "email": "bob@example.com",
  "orderId": 55
}

🔧 Common Operators

  • $mergeObjects, $map, $reduce, $cond

  • $replaceRoot, $addFields, $project