14. Combining Collections with $unionWith

$unionWith combines pipeline output from another collection into the current output stream. Unlike $lookup, it does not attach related documents to each source document. It does not automatically deduplicate equivalent records.

Normalize different source shapes with $project before combining them. If logical duplicates must be removed, define what makes records equivalent and add an explicit deduplication stage.

Example collection requirement

Create the archivedOrders collection before running this example.

Code Example
db.orders.aggregate([
  { $project: { orderId: "$_id", customerId: 1, status: 1, createdAt: 1, source: { $literal: "current" } } },
  {
    $unionWith: {
      coll: "archivedOrders",
      pipeline: [
        { $project: { orderId: "$_id", customerId: 1, status: 1, createdAt: 1, source: { $literal: "archive" } } }
      ]
    }
  },
  { $sort: { createdAt: -1, orderId: -1 } }
]);
Key Takeaways
  • $unionWith combines output streams.
  • It does not automatically deduplicate.
  • Normalize output shapes before combining collections.
  • Consider the volume of data being combined.
Knowledge Check

What is the main distinction between $lookup and $unionWith?