$month (Get Month)

Last updated: 2026-10-09

$month (Get Month)

$month returns the month of a date (1 to 12) — one of the most-used expressions for monthly reports. Pair it with $year as the $group key to build a year-month dimension. It returns an integer without zero padding; use %m of $dateToString for a two-digit string. timezone defines the month boundary and defaults to UTC — always set it for business monthly reports.

CategoryDate
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

{ $month: { date: <date-expression>, timezone: <timezone> } }

⚙️ Parameters

dateRequired; the date expression.
timezoneOptional timezone; defaults to UTC.

Returns:The month (1-12); null if date is null.

▶ Example

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

// $month + $year: order totals by month
 db.orders.aggregate([
  { $group: {
      _id: { y: { $year: { date: '$orderDate' } }, m: { $month: { date: '$orderDate' } } },
      total: { $sum: '$amount' }
  } }
])

Output:

{ "_id": { "y": 2026, "m": 9 }, "total": 45600 }
{ "_id": { "y": 2026, "m": 10 }, "total": 52300 }

📌 Notes

More hands-on cases coming soon.

📚 Related Tutorials

❓ FAQ

QDoes it return 1 to 12?
AYes — January is 1, December is 12.
QHow to output 2026-09 style strings?
AUse the %Y-%m format of $dateToString, or combine $month with $year manually.
QWhy is my monthly stats shifted?
AUsually a timezone issue — pass a local zone like Asia/Shanghai.
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%

🙏 帮我们做得更好

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

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