KeplerGrid guide

Filter joined documents in a MongoDB $lookup pipeline

Put $match inside $lookup.pipeline to filter the documents in the joined array. In this example, customers without paid orders still appear, with an empty paidOrders array.

Join only the paid orders for each customer

Use the synthetic orders and customers from the $facet guide on MongoDB 5.0 or later. The example combines localField, foreignField, and a foreign pipeline in a single $lookup stage.

Open keplergrid_reports.customers in KeplerGrid with a Read only connection that can read both collections. Select Aggregation → JSON, paste the pipeline, and choose Run pipeline.

[
  { "$sort": { "_id": 1 } },
  { "$lookup": {
    "from": "orders",
    "localField": "_id",
    "foreignField": "customerId",
    "pipeline": [
      { "$match": { "status": "paid" } },
      { "$project": { "_id": 1, "status": 1 } },
      { "$sort": { "_id": 1 } }
    ],
    "as": "paidOrders"
  } }
]

For each customer, the equality join matches orders by customerId. The inner $match keeps only paid matches. The inner $project copies the chosen fields into the result array, and its sort orders the matched IDs.

Inspect the joined arrays in KeplerGrid

Switch to Stages and select $lookup. The Input panel shows three customers, and the Output panel shows those three customers with their paidOrders arrays. Select Pipeline results, then JSON view, to read the arrays in the final results.

Expected paid orders by customer
CustomerOrders shown in paidOrders
C-100O-101, O-103
C-200[]
C-300[]

C-200 has orders, but their statuses are pending and cancelled. C-300 has no orders. Both cases produce an empty array after the join.

Return customers with at least one paid order

When the report should include only customers with paid orders, append this $match after $lookup, outside its inner pipeline. Run it again. Testing for the first array element leaves the one customer with a qualifying order, C-100.

{ "$match": { "paidOrders.0": { "$exists": true } } }

For a larger collection, examine the aggregation plan and check index support for the foreign join field, orders.customerId. For the basic equality join, see the $lookup guide. To work with one row per order, see how to unwind a joined array.