KeplerGrid guide

Promote joined MongoDB fields with $replaceWith

Use $replaceWith to promote fields from a joined document to the top level. Set the merge order deliberately so the result keeps the original order ID, and use a fallback for orders with no customer match.

Make the joined fields top-level fields

Load the practice orders and customer. Open keplergrid_transform_lab.orders in KeplerGrid on a Read only connection with access to both collections. Select Aggregation → JSON, paste this pipeline, and choose Run pipeline.

[
  { "$lookup": {
    "from": "customers",
    "localField": "customerId",
    "foreignField": "_id",
    "as": "matchedCustomer"
  } },
  { "$set": {
    "matchedCustomer": {
      "$ifNull": [{ "$arrayElemAt": ["$matchedCustomer", 0] }, null]
    }
  } },
  { "$replaceWith": {
    "$mergeObjects": [
      { "name": null, "tier": null },
      "$matchedCustomer",
      { "_id": "$_id", "customerId": "$customerId", "amount": "$amount" }
    ]
  } },
  { "$sort": { "_id": 1 } }
]

The lookup uses the unique customer _id, so it yields at most one match per order. The next stage picks that object or returns null. $mergeObjects ignores null operands and gives later values precedence when field names collide. The fallback names and order fields ensure that its result is always a document.

Check key collisions and unmatched orders

In Stages, select $replaceWith. For ORD-101, the input contains the order _id and the nested customer’s _id of C-100. The output keeps ORD-101 and gives name and tier top-level positions. The final operand has the order’s ID, so it wins the collision.

The two C-200 orders also remain in the result, with null name and tier. The replacement keeps the order fields named in the final operand. Add any other order fields you need there or choose the fields explicitly in a projection when the joined document includes values you want to omit.

Start with a two-collection lookup or see how to filter the joined documents.

Next, Combine MongoDB documents with $mergeObjects.