$dateTrunc (Truncate Date)

Last updated: 2026-10-09

$dateTrunc (Truncate Date)

$dateTrunc truncates a date to the start of a given unit and returns the new date — perfect for aligning timestamps into hour/day/month buckets for stats. unit supports year, quarter, month, week, day, hour, minute, and second; binSize widens the bucket (e.g. 3-hour buckets). startOfWeek applies only to week. timezone drives the calendar used for truncation — set it explicitly across zones. Introduced in MongoDB 5.0.

CategoryDate
MongoDB Version5.0+
Example Languagemongosh (Shell)

📝 Syntax

{ $dateTrunc: { date: <date-expression>, unit: <unit>, binSize: <number>, timezone: <timezone>, startOfWeek: <week-start> } }

⚙️ Parameters

dateRequired; the date to truncate.
unitRequired; truncation unit: year, quarter, month, week, day, hour, minute, second.
binSizeOptional bucket size that widens the unit.
timezoneOptional timezone for truncation.
startOfWeekOptional; applies only when unit is week.

Returns:The truncated date (BSON Date); null if date is null or missing.

▶ Example

Run the commands below in your local mongosh (requires a running mongod):

// $dateTrunc: aggregate sales by hour
 db.sales.aggregate([
  { $group: {
      _id: { $dateTrunc: { date: '$soldAt', unit: 'hour' } },
      total: { $sum: '$amount' }
  } }
])

Output:

{ "_id": ISODate("2026-09-25T08:00:00Z"), "total": 1250 }
{ "_id": ISODate("2026-09-25T09:00:00Z"), "total": 980 }

📌 Notes

More hands-on cases coming soon.

📚 Related Tutorials

❓ FAQ

QHow is this different from $dateAdd?
A$dateTrunc only aligns to a unit start; $dateAdd moves the time.
QWhat does binSize mean?
AIt widens the unit into buckets — binSize 3 with unit hour gives 3-hour buckets.
QWhat time is the result?
Aday gives 00:00 of that day; hour gives the top of the hour.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏