KeplerGrid guide

Find the latest MongoDB document per customer

Sort orders newest first, group them by customer, and keep the first document in each group. Add a unique tie-breaker so MongoDB picks the same order when two timestamps match.

Sort before taking the first document in each group

Reuse the four synthetic orders from the group-by-day guide. Open keplergrid_daily_orders.orders on your Read only connection in KeplerGrid. Select Aggregation → JSON, paste this pipeline, and choose Run pipeline.

[
  { "$sort": { "customerId": 1, "placedAt": -1, "_id": -1 } },
  { "$group": {
    "_id": "$customerId",
    "latestOrder": { "$first": "$$ROOT" }
  } },
  { "$sort": { "_id": 1 } }
]

The first sort puts each customer's latest timestamp first. For orders with the same timestamp, the higher _id sorts first. $first then keeps the whole selected document as latestOrder. The final sort orders the output by customer ID.

Inspect the input and the winning order

Switch to Stages and select $group. In Input, compare the positions of O-103 and O-102. In Output, check latestOrder._id for each customer. The customer ID is the outer _id.

Expected latest orders for the practice data
CustomerSelected orderReason
C-100O-103It ties with O-102 at 00:30 UTC on June 11 and has the higher ID.
C-200O-201It is this customer's only order.

Click Pipeline results and select JSON view to inspect the complete winning documents.

Test that the tie-breaker controls the result

In the first $sort stage, change "_id": -1 to "_id": 1. Run the pipeline again. Now O-102 wins for C-100 and O-201 still wins for C-200.

For real data, choose the tie-breaker that reflects your reporting rule. The example uses the order ID for a repeatable choice. If you have a sequence or revision that records which event happened later, use it before the unique ID in the sort.

Save and reopen a pipeline to reuse it later, or inspect the execution plan when tuning it for a larger collection.

Next, Get the top N documents per group in MongoDB.