KeplerGrid guide

Combine MongoDB collections with $unionWith

Use $unionWith to append documents from another collection to your aggregation results. A source label shows where each row came from, even when the same order number appears in both collections.

Append archived orders with a source label

Use the two practice collections from the $bucket guide. In KeplerGrid, open keplergrid_aggregation_stages.orders on a Read only connection that can read both collections. Select Aggregation → JSON, paste this pipeline, and choose Run pipeline.

[
  { "$set": { "source": "active" } },
  { "$unionWith": {
    "coll": "archived_orders",
    "pipeline": [
      { "$set": { "source": "archive" } }
    ]
  } },
  { "$sort": { "orderNo": 1, "source": 1, "_id": 1 } }
]

The first $set labels the active rows. The pipeline inside $unionWith runs on archived_orders in the same database and labels its rows. The result contains documents from both sources.

Check both copies of an order number

The final results show seven rows. ORD-102 appears twice, once with source: "active" and once with source: "archive". $unionWith keeps both rows. In the practice data each copy has its own _id.

Two result rows for the same order number
OrderSourceRow ID
ORD-102activeA-102
ORD-102archiveH-102

In Stages, select $unionWith to inspect the active input. Each panel previews up to five documents, so the union output preview might not show the archived rows. Select the final $sort stage to see both ORD-102 rows in its sorted output preview, then select Pipeline results for the complete seven-row sample.

Sort after the union

Use $sort after $unionWith, because the union stage does not guarantee output order. This example sorts by order number, then source, then ID to break ties. If you need to select one record per order number, decide which source should win before grouping.

For a different task, see how to attach related documents with $lookup or export the combined results.