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.
| Customer | Selected order | Reason |
|---|---|---|
C-100 | O-103 | It ties with O-102 at 00:30 UTC on June 11 and has the higher ID. |
C-200 | O-201 | It 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.