MongoDB $dateDiff Operator

Beginner
⏱️ 9 min read
📚 Updated: Jul 2026
🎯 4 Examples
Date Operations

What You’ll Learn

The $dateDiff operator calculates how many time units lie between two dates in MongoDB aggregation pipelines. Use it to measure delivery times, ticket resolution duration, account age, or any elapsed-time metric.

01

Date Difference

Two dates → number.

02

Syntax

startDate, endDate, unit.

03

Time Units

day, hour, year, etc.

04

Timezone

Optional Olson zone.

05

Use Cases

SLA, age, shipping.

06

vs $dateAdd

Measure vs shift.

Definition and Usage

In MongoDB’s aggregation framework, the $dateDiff operator returns an integer count of complete time units between startDate and endDate. For example, if an order was placed on June 1 and delivered on June 8, $dateDiff with unit: "day" returns 7.

💡
Beginner Tip

$dateDiff returns a number, not a date. If endDate is before startDate, the result is negative. Requires MongoDB 5.0+.

📝 Syntax

The $dateDiff operator takes an object with at least three fields:

mongosh
{
  $dateDiff: {
    startDate: <dateExpression>,
    endDate: <dateExpression>,
    unit: <string>,
    timezone: <string>,
    startOfWeek: <string>
  }
}

Syntax Rules

  • startDate — the earlier (or reference) date in the comparison.
  • endDate — the later (or target) date; can be $$NOW.
  • unit — one of: year, quarter, week, day, hour, minute, second, millisecond.
  • timezone — optional Olson timezone ID for calendar-aware calculations.
  • startOfWeek — optional when unit is week (sun, mon, etc.).
  • Returns an integer; partial units are truncated toward zero.

💡 $dateDiff vs $dateAdd vs $dateSubtract

$dateDiff — two dates → number of units between them
$dateAdd — one date + N units → new date
$dateSubtract — one date − N units → new date

⚡ Quick Reference

QuestionAnswer
Operator typeAggregation expression operator (date)
Required fieldsstartDate, endDate, unit
Return typeInteger (number of units)
Supported unitsyear, quarter, week, day, hour, minute, second, millisecond
MongoDB version5.0+
Days between
{
  $dateDiff: {
    startDate: "$orderedAt",
    endDate: "$deliveredAt",
    unit: "day"
  }
}

Shipping duration

Age in years
{
  $dateDiff: {
    startDate: "$birthDate",
    endDate: "$$NOW",
    unit: "year"
  }
}

Years since birth

Hours open
{
  $dateDiff: {
    startDate: "$openedAt",
    endDate: "$closedAt",
    unit: "hour"
  }
}

Ticket resolution time

With timezone
{
  $dateDiff: {
    startDate: "$start",
    endDate: "$end",
    unit: "day",
    timezone: "UTC"
  }
}

Timezone-aware diff

Examples Gallery

Measure shipping days, ticket resolution hours, account age, and timezone-aware elapsed time with $dateDiff.

📚 Days Between Two Dates

Use an orders collection and compute shipping duration from order to delivery.

Sample Input Documents

Suppose you have an orders collection with order and delivery timestamps:

mongosh
[
  {
    "_id": ObjectId("609c26812e9274a86871bc6a"),
    "item": "Laptop",
    "orderedAt":   ISODate("2024-06-01T10:00:00Z"),
    "deliveredAt": ISODate("2024-06-08T14:30:00Z")
  },
  {
    "_id": ObjectId("609c26812e9274a86871bc6b"),
    "item": "Mouse",
    "orderedAt":   ISODate("2024-06-10T09:00:00Z"),
    "deliveredAt": ISODate("2024-06-12T11:00:00Z")
  }
]

Example 1 — Shipping Days with $dateDiff

Calculate how many full days passed between order and delivery:

mongosh
db.orders.aggregate([
  {
    $project: {
      item: 1,
      orderedAt: 1,
      deliveredAt: 1,
      shippingDays: {
        $dateDiff: {
          startDate: "$orderedAt",
          endDate: "$deliveredAt",
          unit: "day"
        }
      }
    }
  }
])

How It Works

  • $dateDiff counts complete calendar days between the two timestamps.
  • Laptop: June 1 → June 8 = 7 days.
  • Mouse: June 10 → June 12 = 2 days.

📈 Practical Patterns

Resolution time in hours, account age, and filtering by duration.

Example 2 — Ticket Resolution Time in Hours

Measure how many hours a support ticket stayed open:

mongosh
db.tickets.aggregate([
  {
    $project: {
      title: 1,
      openedAt: 1,
      closedAt: 1,
      hoursOpen: {
        $dateDiff: {
          startDate: "$openedAt",
          endDate: "$closedAt",
          unit: "hour"
        }
      }
    }
  }
])

// openedAt: 2024-06-01 09:00, closedAt: 2024-06-01 17:00 → hoursOpen: 8

How It Works

Use finer units like hour, minute, or millisecond when day-level precision is too coarse for SLAs or performance metrics.

Example 3 — Account Age in Years

Calculate how many years a user has been registered using $$NOW:

mongosh
db.users.aggregate([
  {
    $project: {
      name: 1,
      registeredAt: 1,
      accountAgeYears: {
        $dateDiff: {
          startDate: "$registeredAt",
          endDate: "$$NOW",
          unit: "year"
        }
      }
    }
  }
])

How It Works

$$NOW is the current server time when the pipeline runs. The year unit returns whole years elapsed, useful for loyalty tiers or retention analysis.

Example 4 — Filter Orders Shipped Within 3 Days

Combine $dateDiff with $match to find fast deliveries:

mongosh
db.orders.aggregate([
  {
    $addFields: {
      shippingDays: {
        $dateDiff: {
          startDate: "$orderedAt",
          endDate: "$deliveredAt",
          unit: "day"
        }
      }
    }
  },
  {
    $match: {
      shippingDays: { $lte: 3 }
    }
  },
  {
    $project: {
      item: 1,
      shippingDays: 1
    }
  }
])

How It Works

Compute the difference in $addFields, then filter in a later $match stage. This pattern supports SLA reporting and quality dashboards.

🚀 Use Cases

  • Shipping and fulfillment — measure days from order to delivery for logistics KPIs.
  • Support SLAs — track hours or minutes tickets remain open before resolution.
  • User analytics — compute account age, subscription tenure, or time since last login.
  • Compliance reporting — verify events occurred within required time windows.

🧠 How $dateDiff Works

1

MongoDB resolves both dates

startDate and endDate are evaluated per document — fields, $$NOW, or literals.

Input
2

$dateDiff counts units

MongoDB calculates complete units between the dates, optionally using timezone.

Calculate
3

An integer is returned

The count is stored in the field you define — ready for sorting, filtering, or grouping.

Output
=

Elapsed time as a number

Use in $match, $group, charts, or alongside $dateAdd for scheduling.

Conclusion

The $dateDiff operator is the clearest way to measure elapsed time between two dates in MongoDB aggregation pipelines. It replaces manual millisecond subtraction and division with readable, unit-based date math.

Use $dateAdd when you need a future or past date, and $dateDiff when you need how long something took. Always ensure both operands are BSON dates and that your MongoDB deployment is version 5.0 or later.

💡 Best Practices

✅ Do

  • Store dates as BSON Date type, not strings
  • Pick the right unit for your business question
  • Use timezone when calendar days depend on locale
  • Use $$NOW for “time since” calculations
  • Combine with $match for SLA and threshold filters

❌ Don’t

  • Expect fractional units — results are truncated integers
  • Use $dateDiff on MongoDB versions before 5.0
  • Confuse $dateDiff with $dateAdd
  • Pass invalid unit strings (no month unit exists)
  • Swap startDate and endDate without expecting negative values

Key Takeaways

Knowledge Unlocked

Five things to remember about $dateDiff

Use these points when measuring time between dates in MongoDB.

5
Core concepts
📝 02

Three Fields

start, end, unit.

Syntax
🛠 03

Integer Result

Truncated units.

Output
🌐 04

Timezone

Optional Olson ID.

Option
05

Not $dateAdd

Measure vs shift.

Important

❓ Frequently Asked Questions

$dateDiff returns the number of time units between two dates. It answers questions like how many days passed between an order and delivery, or how many hours a ticket stayed open.
{ $dateDiff: { startDate: <date>, endDate: <date>, unit: <string>, timezone: <string>, startOfWeek: <string> } }. startDate, endDate, and unit are required.
year, quarter, week, day, hour, minute, second, and millisecond. There is no "month" unit. Pass the unit as a string such as "day" or "hour".
$dateDiff measures the gap between two dates and returns a number. $dateAdd adds units to one date and returns a new date.
$dateDiff is available in MongoDB 5.0 and later in aggregation pipelines and update pipelines that use aggregation expressions.

Continue the Operator Series

Move on to $dateFromParts to build dates from components, or review $dateAdd for forward date math.

Next: $dateFromParts →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

5 people found this page helpful