MongoDB $dateDiff Operator

Beginner
5 min read
Updated: Oct 2026
3 examples
Live preview

What Is $dateDiff?

$dateDiff is a MongoDB aggregation expression that returns how many time units separate two dates. The result is a truncated integer (whole units only). If endDate is earlier, the result is negative.

Remember
$dateDiff = whole units between start and end

{
  $dateDiff: {
    startDate: <date>,
    endDate: <date>,
    unit: "<unit>",
    timezone: "<tz>",      // optional
    startOfWeek: "<day>"   // optional (week)
  }
}

units: year, quarter, month, week, day,
       hour, minute, second, millisecond

partial units → truncated (not rounded up)
null date → null
UsePrefer
Measure gap between two dates$dateDiff
Move a date forward by units$dateAdd
Move a date backward$dateSubtract

How to Use $dateDiff in MongoDB

Name the earlier date, the later date, and the unit you want to count.

  1. Choose an expression stage ($addFields or $project).
  2. Set startDate and endDate to Date fields or expressions.
  3. Set unit (for example "day" or "hour").
  4. Optionally set timezone or startOfWeek when those boundaries matter.
PieceRequired?Role
startDateYesBeginning of the interval
endDateYesEnd of the interval
unitYesWhat to count (day, hour, month, …)
timezone / startOfWeekNoBoundary rules for some units

Pseudocode

Pseudocode
for each document:
    start = evaluate(startDate)
    end   = evaluate(endDate)
    unit  = evaluate(unit)
    if start or end is null or missing:
        result = null
    else:
        result = truncated whole units from start to end
        // negative if end < start
    emit { ..., field: result }

Cheat Sheet

Keep these facts handy while measuring date gaps.

TopicDetail
TypeAggregation expression (not a find filter)
Syntax{ $dateDiff: { startDate, endDate, unit } }
ResultTruncated integer (whole units)
NegativeWhen endDate < startDate
vs $dateAddDiff → number; Add → new date
Common unitsday, hour, month, week
Sample check2026-01-10 → 2026-01-17 = 7 days

Live Preview

Watch $dateDiff count whole days or hours between two loan dates.

Simulates $dateDiff from start date 2026-01-10 (UTC midnight).

Result
startDate = 2026-01-10T00:00:00.000Z
endDate   = 2026-01-17T00:00:00.000Z
unit = "day"
$result → 7

Worked Walkthrough — Loan Length

A book was borrowed on 2026-01-10 and returned on 2026-01-17. How many whole days was it out?

Calculation
Document:
  {
    borrowedOn: 2026-01-10,
    returnedOn: 2026-01-17
  }

$dateDiff:
  startDate = borrowedOn
  endDate   = returnedOn
  unit      = "day"

2026-01-10 → 2026-01-17 = 7 whole days ✓

MongoDB Examples

We use one library loan with borrow and return dates. First count days, then count hours. Run these in mongosh after inserting the sample data once.

Example 1 — Sample Data

Imagine one library loan borrowed on 2026-01-10 and returned on 2026-01-17. We save both dates in a collection named loans.

mongosh
db.loans.insertOne({
  _id: 1,
  task: "Library book",
  borrowedOn: ISODate("2026-01-10T00:00:00Z"),
  returnedOn: ISODate("2026-01-17T00:00:00Z")
});

How the Data Is Stored in MongoDB

After the insert, MongoDB keeps one document in loans. Run find() to see it:

mongosh
db.loans.find()

Read that document like this:

Field in MongoDBValuePlain English
_id1Document id (row number for this lesson)
task"Library book"What was borrowed
borrowedOn2026-01-10Start of the loan
returnedOn2026-01-17End of the loan
Picture
Timeline:

  borrowedOn              returnedOn
  2026-01-10  ----------  2026-01-17
                 |
            7 whole days

Same gap in hours: 7 * 24 = 168

How It Works

  1. Insert once. insertOne adds a single loan document to loans.
  2. Store real Dates. Both fields use ISODate(...), not strings.
  3. find() shows the same shape. Ready for $dateDiff in the next examples.

Example 2 — Diff in Days

Goal: compute daysOut as whole days from borrow to return.

mongosh
db.loans.aggregate([
  {
    $addFields: {
      daysOut: {
        $dateDiff: {
          startDate: "$borrowedOn",
          endDate: "$returnedOn",
          unit: "day"
        }
      }
    }
  }
]);

How It Works

  1. Read both dates. MongoDB already has borrow and return from Example 1.
  2. Count day units. unit: "day" asks for whole days only.
  3. Store the number. $addFields writes daysOut: 7.

Example 3 — Diff in Hours

Same loan, but count the gap in hours instead of days.

mongosh
db.loans.aggregate([
  {
    $addFields: {
      hoursOut: {
        $dateDiff: {
          startDate: "$borrowedOn",
          endDate: "$returnedOn",
          unit: "hour"
        }
      }
    }
  }
]);

How It Works

  1. Same stored document. Still using Jan 10 → Jan 17 from Example 1.
  2. Change only the unit. unit: "hour" counts hours instead of days.
  3. Easy check. 7 days × 24 hours = 168.

Edge Cases & Pitfalls

Check these before using $dateDiff in production pipelines.

trunc

Partial units are truncated

A 23-hour gap with unit: "day" returns 0. Use a finer unit when fractions matter.

order

End before start → negative

Swap dates if you always want a positive duration, or take the absolute value afterward.

vs subtract

Not the same as $subtract

$subtract on two dates returns milliseconds. Prefer $dateDiff for day/month/hour counts.

null

Null dates stay null

If either date is missing or null, the result is null. Validate both sides before measuring.

Performance Notes

ApproachCostBest for
$dateDiff per documentCheap date mathDurations, SLAs, loan lengths
Diff then $matchCompute on scanned docsFilter after computing a duration
Store duration on writeNo recompute on readHot queries on the same gap

Date diffs are cheap compared with large sorts or joins. Filter early with $match when only some documents need a duration.

Key Takeaways

  • Role: count whole units between two dates.
  • Required: startDate, endDate, unit.
  • Result: truncated integer; can be negative.
  • Sibling: use $dateAdd when you need a new date, not a count.

One line: $dateDiff answers “how many whole units between these two dates?”

Frequently Asked Questions

$dateDiff returns how many time units separate two dates—for example days between borrowedOn and returnedOn. Use it inside aggregation stages such as $project and $addFields.
Use { $dateDiff: { startDate: <date>, endDate: <date>, unit: <string>, timezone: <tz>, startOfWeek: <string> } }. startDate, endDate, and unit are required.
Supported units include year, quarter, month, week, day, hour, minute, second, and millisecond. 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.
Yes. If endDate is earlier than startDate, $dateDiff returns a negative number.
No. $dateDiff returns a truncated integer—only whole units count. Less than one full day with unit "day" returns 0.

Next: $dateFromParts

Build a Date from year, month, day, and time parts.

$dateFromParts tutorial →

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.

9 people found this page helpful