KeplerGrid guide

Measure time between MongoDB dates with $dateDiff

Use $dateDiff when you need to count time-unit boundaries between two dates. An order can cross midnight in UTC while staying on the same calendar day in New York.

Count minutes and calendar-day boundaries

Use MongoDB 5.0 or later and the practice orders. In KeplerGrid, open keplergrid_aggregation_stages.orders with a Read only connection. Select Aggregation → JSON, paste the pipeline, and choose Run pipeline.

[
  { "$match": {
    "$expr": { "$and": [
      { "$eq": [{ "$type": "$placedAt" }, "date"] },
      { "$eq": [{ "$type": "$deliveredAt" }, "date"] }
    ] }
  } },
  { "$set": {
    "minutes": { "$dateDiff": {
      "startDate": "$placedAt", "endDate": "$deliveredAt", "unit": "minute"
    } },
    "utcDays": { "$dateDiff": {
      "startDate": "$placedAt", "endDate": "$deliveredAt", "unit": "day"
    } },
    "newYorkDays": { "$dateDiff": {
      "startDate": "$placedAt", "endDate": "$deliveredAt",
      "unit": "day", "timezone": "America/New_York"
    } }
  } },
  { "$project": { "_id": 0, "orderNo": 1, "minutes": 1, "utcDays": 1, "newYorkDays": 1 } },
  { "$sort": { "orderNo": 1 } }
]

The sample stores timestamps as BSON Dates. The filter keeps the four practice rows with both dates and leaves out ORD-104, which has no delivery timestamp. Leaving timezone out uses UTC.

Inspect the results around midnight

In Stages, select $set. Compare the dates in Input with the three calculated values in Output. Select Pipeline results to see the four sorted rows.

Expected time boundaries crossed
OrderMinutesUTC daysNew York days
ORD-1003010
ORD-1013001
ORD-102150011
ORD-10327000

ORD-100 runs from 23:45 to 00:15 UTC, so it crosses a UTC midnight. ORD-101 runs from 04:50 to 05:20 UTC on the same date, which is 23:50 to 00:20 in New York in January.

Choose between calendar units and elapsed time

$dateDiff returns an integer count of boundaries. With unit: "day", a result of 1 can mean crossing midnight during a short delivery. For an exact duration in milliseconds between two BSON Dates, use $subtract with the delivery date first and the placed date second. Use a named time zone for local calendar rules that account for daylight saving.

To group timestamps by their calendar date, see how to group MongoDB orders by day.