$dateDiff (Date Difference)
Last updated: 2026-10-09
$dateDiff (Date Difference)
$dateDiff computes the difference between two dates in a given unit as an integer — ideal for ages, subscription lengths, or dwell times. unit supports year, month, week, day, hour, minute, second, and millisecond; results truncate to whole-unit boundaries (year counts only complete years). startOfWeek sets the week start and applies only when unit is week. timezone drives the calendar used; always set it across zones.
| Category | Date |
|---|---|
| MongoDB Version | 5.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $dateDiff: { startDate: <date-expression>, endDate: <date-expression>, unit: <unit>, timezone: <timezone>, startOfWeek: <week-start> } }
⚙️ Parameters
| startDate / endDate | Required; the start and end dates. |
|---|---|
| unit | Required; the difference unit (the 8 units above). |
| timezone | Optional timezone for the calculation. |
| startOfWeek | Optional; applies only when unit is week; values like Monday, Sunday. |
Returns:The integer difference (endDate minus startDate); null if either date is null.
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $dateDiff: compute age in years
db.users.aggregate([
{ $project: {
ageYears: { $dateDiff: { startDate: '$birthDate', endDate: '$$NOW', unit: 'year' } }
} }
])
Output:
{ "_id": 1, "ageYears": 28 }
{ "_id": 2, "ageYears": 31 }
📌 Notes
- Result is endDate minus startDate and may be negative
- Larger units truncate to complete boundaries: year counts full years only
- startOfWeek applies only to unit week; values Monday through Sunday
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QDoes the result have decimals?
ANo — $dateDiff returns integers, truncated at unit boundaries.
QCan the difference be negative?
AYes — negative when endDate is earlier than startDate.
QHow to count days between two dates?
ASet unit to day; note timezone shifts calendar-day boundaries.