Unwind the joined orders array
Reuse the synthetic customers and orders from the $lookup guide. In KeplerGrid, open keplergrid_lookup.customers on the same Read only connection. Select Aggregation → JSON, paste this pipeline, and click Run pipeline.
[
{ "$lookup": {
"from": "orders",
"localField": "_id",
"foreignField": "customerId",
"as": "orders"
} },
{ "$unwind": {
"path": "$orders",
"preserveNullAndEmptyArrays": true
} },
{ "$project": {
"_id": 0,
"customerId": "$_id",
"orderId": { "$ifNull": ["$orders._id", null] },
"item": { "$ifNull": ["$orders.item", null] }
} },
{ "$sort": { "customerId": 1, "orderId": 1 } }
]
$unwind makes a copy of the customer document for each order and replaces the orders array with that order. The projection gives the result three columns and makes the missing order fields explicit as null. The final sort puts the rows in a repeatable order for comparison.
Watch three customer documents become four rows
Switch to Stages and select $unwind. Under Input, C-100 has two orders in an array and C-300 has an empty array. Under Output, C-100 appears twice, once per order. C-300 still appears, with the orders field absent. The later projection turns that absence into explicit null values.
Click Pipeline results and select Table view to see the final rows.
| Customer ID | Order ID | Item |
|---|---|---|
C-100 | O-101 | Notebook |
C-100 | O-102 | Pencils |
C-200 | O-201 | Envelopes |
C-300 | null | null |
Compare the default behavior
Replace the $unwind stage with the shorthand below and run the pipeline again. It returns three rows because the empty orders array for C-300 is dropped. Restore the earlier stage to bring that customer back.
{ "$unwind": "$orders" }
With the preserve option enabled, this result has four rows and three actual orders. If you count orders downstream, count the rows with an order ID.
See how $lookup builds the original array or export your pipeline results to CSV or JSON.
After unwinding, promote the joined document with $replaceWith and choose which fields to keep.