MongoDB $year Operator

Beginner
⏱️ 8 min read
📚 Updated: Jul 2026
🎯 5 Examples
Date Operations

What You’ll Learn

The $year operator extracts the calendar year from a BSON date inside MongoDB aggregation pipelines. Use it to group sales by year, filter documents from a specific year, or build year-month report keys with $month.

01

Extract Year

Date → 2024.

02

Syntax

One date argument.

03

$group Keys

Annual reports.

04

+$month

Year-month buckets.

05

+$week

Year-week keys.

06

vs $isoWeekYear

Calendar vs ISO.

Definition and Usage

In MongoDB’s aggregation framework, the $year operator takes a date expression and returns an integer representing the calendar year. For example, $year on ISODate("2024-06-15T00:00:00Z") returns 2024.

This is one of the most common date operators for analytics. Combine it with $month for monthly trends, $week for weekly breakdowns, or use it alone to compare annual totals across years.

💡
Beginner Tip

$year returns the calendar year in UTC. For ISO week-based reporting where year boundaries differ, use $isoWeekYear with $isoWeek instead.

📝 Syntax

The $year operator takes a single date expression:

mongosh
{ $year: <dateExpression> }

Common Patterns

mongosh
// Extract year from a field
{ $year: "$orderDate" }

// Group sales by year
{
  $group: {
    _id: { $year: "$orderDate" },
    total: { $sum: "$amount" }
  }
}

// Filter documents from 2024
{
  $match: {
    $expr: {
      $eq: [ { $year: "$orderDate" }, 2024 ]
    }
  }
}

// Year + month grouping key
{
  year: { $year: "$orderDate" },
  month: { $month: "$orderDate" }
}

Syntax Rules

  • Argument — any expression that evaluates to a BSON Date.
  • Return value — integer calendar year (e.g. 2023, 2024) in UTC.
  • Null input — returns null when the date is null or missing.
  • Use inside $project, $addFields, $group, or $match with $expr.
  • Available in MongoDB 3.4+ aggregation and update pipelines with expressions.

💡 $year vs $isoWeekYear vs $month

$year — calendar year (wall-calendar year in UTC)
$isoWeekYear — ISO week-numbering year (can differ near Jan/Dec)
$month — month number 1–12, not a year extractor
See the $isoWeekYear operator for ISO calendar reporting

⚡ Quick Reference

QuestionAnswer
Operator typeAggregation expression operator (date extraction)
Syntax{ $year: <dateExpression> }
Return typeInteger (calendar year)
TimezoneUTC (use $dateToParts for local/timezone-aware)
Common stages$project, $addFields, $group, $match + $expr
MongoDB version3.4+
From field
{
  $year: "$orderDate"
}

Year of orderDate

Literal date
{
  $year: ISODate("2024-06-15")
}

Returns 2024

Group by year
{
  _id: {
    $year: "$orderDate"
  }
}

Annual totals

Filter 2024
{
  $expr: {
    $eq: [
      { $year: "$d" },
      2024
    ]
  }
}

Year filter

Examples Gallery

Extract years, group revenue by calendar year, filter 2024 orders, and build year-month keys with an orders collection.

📚 Extract the Year from a Date

Add a year field from orderDate with $project.

Sample Input Documents

Suppose you have an orders collection spanning multiple years:

mongosh
[
  {
    "_id": 1,
    "customer": "Alice",
    "orderDate": ISODate("2023-11-20T10:00:00Z"),
    "amount": 450.00
  },
  {
    "_id": 2,
    "customer": "Bob",
    "orderDate": ISODate("2024-03-15T14:30:00Z"),
    "amount": 320.00
  },
  {
    "_id": 3,
    "customer": "Carol",
    "orderDate": ISODate("2024-12-01T09:00:00Z"),
    "amount": 890.00
  },
  {
    "_id": 4,
    "customer": "Dave",
    "orderDate": ISODate("2025-01-10T16:00:00Z"),
    "amount": 125.00
  }
]

Example 1 — Basic $year Extraction

Add the calendar year alongside each order:

mongosh
db.orders.aggregate([
  {
    $project: {
      customer: 1,
      orderDate: 1,
      amount: 1,
      orderYear: { $year: "$orderDate" }
    }
  }
])

How It Works

$year reads the UTC calendar year from the BSON date and returns it as an integer.

📈 Grouping & Filtering by Year

Build annual reports, filter a specific year, and combine with month or week.

Example 2 — Group Revenue by Year

Summarize total sales per calendar year:

mongosh
db.orders.aggregate([
  {
    $group: {
      _id: { $year: "$orderDate" },
      orderCount: { $sum: 1 },
      totalRevenue: { $sum: "$amount" }
    }
  },
  { $sort: { _id: 1 } }
])

// { _id: 2023, orderCount: 1, totalRevenue: 450.00 }
// { _id: 2024, orderCount: 2, totalRevenue: 1210.00 }
// { _id: 2025, orderCount: 1, totalRevenue: 125.00 }

How It Works

Using $year as the _id in $group creates one bucket per calendar year. This is the standard pattern for annual dashboards.

Example 3 — Filter Orders from 2024

Keep only documents where the order year equals 2024:

mongosh
db.orders.aggregate([
  {
    $match: {
      $expr: {
        $eq: [ { $year: "$orderDate" }, 2024 ]
      }
    }
  },
  {
    $project: {
      customer: 1,
      orderDate: 1,
      amount: 1
    }
  }
])

// Returns Bob and Carol (2024 orders only)

How It Works

$expr enables date expressions inside $match. Compare the extracted year to a literal integer for flexible year-based filtering.

Example 4 — Group by Year and Month

Build monthly revenue broken down by year:

mongosh
db.orders.aggregate([
  {
    $group: {
      _id: {
        year: { $year: "$orderDate" },
        month: { $month: "$orderDate" }
      },
      totalRevenue: { $sum: "$amount" }
    }
  },
  { $sort: { "_id.year": 1, "_id.month": 1 } }
])

// { _id: { year: 2024, month: 3 },  totalRevenue: 320.00 }
// { _id: { year: 2024, month: 12 }, totalRevenue: 890.00 }

How It Works

Pairing $year with $month creates unique year-month keys for time-series charts and seasonal analysis.

Example 5 — Pair $year with $week

Create unique year-week grouping keys for weekly reports:

mongosh
db.orders.aggregate([
  {
    $group: {
      _id: {
        year: { $year: "$orderDate" },
        week: { $week: "$orderDate" }
      },
      totalRevenue: { $sum: "$amount" }
    }
  },
  { $sort: { "_id.year": 1, "_id.week": 1 } }
])

How It Works

Week numbers repeat every year, so always include $year when grouping by $week. See the $week operator tutorial for week-number details.

Bonus — Compare $year and $isoWeekYear

Near year boundaries, calendar year and ISO week year can differ:

mongosh
db.orders.aggregate([
  {
    $project: {
      orderDate: 1,
      calendarYear: { $year: "$orderDate" },
      isoWeekYear: { $isoWeekYear: "$orderDate" },
      isoWeek: { $isoWeek: "$orderDate" }
    }
  }
])

// 2023-01-01 may show:
//   calendarYear: 2023, isoWeekYear: 2022, isoWeek: 52

How It Works

Use $year for standard calendar reporting. Use $isoWeekYear when your business follows ISO 8601 week numbering.

🚀 Use Cases

  • Annual revenue reports — group sales, sign-ups, or events by calendar year.
  • Year-over-year comparison — compare totals across consecutive years in dashboards.
  • Year filters — show only documents from the current or a selected year.
  • Composite time keys — combine with $month or $week for finer breakdowns.
  • Data partitioning logic — derive year labels for archival or export jobs.

🧠 How $year Works

1

MongoDB resolves the date

The input expression is evaluated per document — a field, literal ISODate, or nested date expression.

Input
2

Calendar year is extracted

MongoDB reads the UTC year component from the BSON date (e.g. 2024).

Extract
3

An integer is returned

The year is ready for $group, $match, or display in projected fields.

Output
=

Year for time-based analytics

Combine with $month, $week, or $dayOfYear for richer reporting.

Conclusion

The $year operator extracts the calendar year from BSON dates in MongoDB aggregation pipelines. It is essential for annual reports, year filters, and composite time keys with $month or $week.

Remember: results are in UTC, and ISO week reporting needs $isoWeekYear instead. Next in the series: $zip.

💡 Best Practices

✅ Do

  • Use $year for standard calendar-year grouping and filtering
  • Pair with $month or $week for composite time keys
  • Store BSON dates for reliable year extraction
  • Use $dateToParts when timezone-aware years matter
  • Sort grouped results by year for chronological charts

❌ Don’t

  • Use $year for ISO week-year reporting (use $isoWeekYear)
  • Group by $week without also including $year
  • Assume local timezone — default extraction is UTC
  • Parse string dates directly — convert with $dateFromString first
  • Confuse $year with $dayOfYear (day 1–366 within a year)

Key Takeaways

Knowledge Unlocked

Five things to remember about $year

Use these points when extracting years from dates in MongoDB.

5
Core concepts
📝 02

One Argument

Date expression.

Syntax
🛠 03

$group Key

Annual totals.

Pattern
🗃 04

+ $month

Year-month keys.

Combine
05

vs $isoWeekYear

Calendar vs ISO.

Compare

❓ Frequently Asked Questions

$year returns the calendar year (e.g. 2024) for a BSON Date. It is an aggregation expression operator used inside stages like $project, $addFields, and $group.
The syntax is { $year: <dateExpression> }. Pass a field reference like "$orderDate", a literal ISODate, or another expression that evaluates to a date.
$year returns the calendar year shown on a wall calendar. $isoWeekYear returns the ISO week-numbering year, which can differ near January and December when a date falls in week 52 or week 1 of an adjacent ISO year.
$year extracts the year in UTC. For timezone-aware year extraction, use $dateToParts with a timezone field and read the year component.
$year returns null when the input date is null or refers to a missing field. It does not throw an error.

Continue the Operator Series

Move on to $zip for merging arrays element-wise, or review $month for month extraction.

Next: $zip →

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