MongoDB $week Operator

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

What You’ll Learn

The $week operator extracts the week of the year (0–53) from a BSON date inside MongoDB aggregation pipelines. Use it to build weekly sales reports, group events by calendar week, or filter documents from a specific week.

01

Week Number

Date → 0–53.

02

Syntax

One date argument.

03

Sunday Start

MongoDB calendar.

04

Pair with $year

Year + week keys.

05

Use Cases

Weekly reports.

06

vs $isoWeek

ISO vs MongoDB.

Definition and Usage

In MongoDB’s aggregation framework, the $week operator takes a date expression and returns an integer from 0 to 53 representing the week of the year. MongoDB weeks start on Sunday, and week 1 is the week that contains the first Sunday of the year.

This is useful for weekly dashboards, trend analysis, and grouping time-series data when your organization follows a Sunday-based calendar. For ISO 8601 week numbering (Monday start), use $isoWeek instead.

💡
Beginner Tip

Week numbers repeat every year, so always combine $week with $year when grouping. Otherwise, week 10 from 2023 and week 10 from 2024 land in the same bucket.

📝 Syntax

The $week operator takes a single date expression:

mongosh
{ $week: <dateExpression> }

Common Patterns

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

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

// Filter a specific week
{
  $match: {
    $expr: {
      $and: [
        { $eq: [ { $year: "$orderDate" }, 2024 ] },
        { $eq: [ { $week: "$orderDate" }, 25 ] }
      ]
    }
  }
}

Syntax Rules

  • Argument — any expression that evaluates to a BSON Date.
  • Return value — integer 0–53 in UTC.
  • Week starts on — Sunday; week 1 contains the first Sunday of the year.
  • Null input — returns null when the date is null or missing.
  • Use inside $project, $addFields, $group, or $match with $expr.

💡 $week vs $isoWeek vs $dayOfWeek

$week — week of year 0–53, weeks start on Sunday
$isoWeek — ISO week 1–53, weeks start on Monday (ISO 8601)
$dayOfWeek — weekday 1–7 (Sun–Sat), not week of year
See the $isoWeek operator tutorial for ISO calendar reporting

⚡ Quick Reference

QuestionAnswer
Operator typeAggregation expression operator (date extraction)
Syntax{ $week: <dateExpression> }
Return typeInteger (0–53)
Week starts onSunday
Pair with$year for unique year-week keys
MongoDB version3.4+
From field
{
  $week: "$orderDate"
}

Week of orderDate

Year + week
{
  year: { $year: "$d" },
  week: { $week: "$d" }
}

Group key pattern

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

Returns week number

Null input
null

Returns null

Examples Gallery

Extract week numbers, group sales by year and week, filter a specific week, and compare with $isoWeek using an orders collection.

📚 Extract the Week from a Date

Add a week number field from orderDate with $project.

Sample Input Documents

Suppose you have an orders collection with order timestamps:

mongosh
[
  {
    "_id": 1,
    "customer": "Alice",
    "orderDate": ISODate("2024-06-10T14:30:00Z"),
    "amount": 120.00
  },
  {
    "_id": 2,
    "customer": "Bob",
    "orderDate": ISODate("2024-06-15T09:00:00Z"),
    "amount": 85.50
  },
  {
    "_id": 3,
    "customer": "Carol",
    "orderDate": ISODate("2024-06-17T16:45:00Z"),
    "amount": 210.00
  }
]

Example 1 — Basic $week Extraction

Add the week number alongside each order:

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

How It Works

$week returns the Sunday-based week number. Including $year alongside it makes the result easier to interpret in reports.

📈 Weekly Reporting Patterns

Group revenue by week, filter a specific week, and compare calendar systems.

Example 2 — Group Sales by Year and Week

Build a weekly revenue summary:

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

// Example bucket:
// { _id: { year: 2024, week: 24 }, orderCount: 5, totalRevenue: 1250.00 }

How It Works

Combining $year and $week in _id creates a unique key for each calendar week. Without $year, weeks from different years would merge incorrectly.

Example 3 — Filter Orders from a Specific Week

Find all orders from week 25 of 2024:

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

How It Works

$expr lets you use date expressions inside $match. Always filter by both year and week to avoid pulling data from the same week number in other years.

Example 4 — Weekly Trend with Formatted Label

Create a readable week label for dashboards:

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

// weekLabel: "2024-W24" → totalRevenue: 1250.00

How It Works

Pair $week with $concat and $toString to produce human-readable labels like 2024-W24 for charts and exports.

Example 5 — Compare $week and $isoWeek

See how MongoDB calendar weeks differ from ISO weeks on the same dates:

mongosh
db.orders.aggregate([
  {
    $project: {
      orderDate: 1,
      mongoWeek: { $week: "$orderDate" },
      isoWeek: { $isoWeek: "$orderDate" }
    }
  }
])

// Dates near year boundaries or Mondays can show
// different week numbers between $week and $isoWeek

How It Works

$week uses Sunday-based weeks; $isoWeek uses ISO 8601 Monday-based weeks. Pick one convention and use it consistently across your reports.

Bonus — $week on a Literal Date

Test week extraction on a fixed ISODate:

mongosh
db.orders.aggregate([
  {
    $project: {
      demo: {
        $week: ISODate("2024-01-01T00:00:00Z")
      }
    }
  }
])

// January 1, 2024 was a Monday.
// $week returns 0 because the first Sunday of 2024
// had not yet occurred in MongoDB's calendar.

How It Works

Early January dates often fall in week 0 because MongoDB week 1 starts on the first Sunday. This is why pairing with $year and understanding the calendar rules matters.

🚀 Use Cases

  • Weekly sales reports — group revenue and order counts by year and week.
  • Trend dashboards — chart week-over-week growth in aggregation pipelines.
  • Event analytics — measure sign-ups or logins per calendar week.
  • Operational windows — filter documents from a specific week for audits.
  • Data quality checks — verify date fields fall in expected week ranges.

🧠 How $week Works

1

MongoDB resolves the date

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

Input
2

Week number is calculated

MongoDB counts weeks from the first Sunday of the year in UTC, returning 0–53.

Extract
3

An integer is returned

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

Output
=

Week-of-year for reporting

Combine with $year, $month, or $isoWeek for richer calendar logic.

Conclusion

The $week operator extracts week-of-year numbers from BSON dates in MongoDB aggregation pipelines. Its Sunday-based calendar and 0–53 range are the key details to remember when building weekly reports.

Always pair $week with $year when grouping. For ISO Monday-based weeks, use $isoWeek and $isoWeekYear. Next in the series: $where.

💡 Best Practices

✅ Do

  • Always pair $week with $year in $group keys
  • Use $isoWeek when your team expects ISO 8601 numbering
  • Store BSON dates for reliable week extraction
  • Document whether reports use MongoDB weeks or ISO weeks
  • Sort by year then week for chronological weekly trends

❌ Don’t

  • Group by $week alone without $year
  • Confuse $week with $dayOfWeek (weekday 1–7)
  • Mix $week and $isoWeek in one dashboard without labels
  • Assume week 1 starts on January 1
  • Parse string dates — convert with $dateFromString first

Key Takeaways

Knowledge Unlocked

Five things to remember about $week

Use these points when extracting weeks from dates in MongoDB.

5
Core concepts
📝 02

One Argument

Date expression.

Syntax
🛠 03

Sunday Start

Week 1 = 1st Sun.

Calendar
🗃 04

+ $year

Unique week keys.

Pattern
05

vs $isoWeek

ISO Monday weeks.

Compare

❓ Frequently Asked Questions

$week returns the week of the year for a BSON Date as an integer from 0 to 53. It is an aggregation expression operator used inside stages like $project, $addFields, and $group.
The syntax is { $week: <dateExpression> }. Pass a field reference like "$orderDate", a literal ISODate, or another expression that evaluates to a date.
MongoDB weeks start on Sunday. Week 1 is the week that contains the first Sunday of the year. This differs from $isoWeek, which follows ISO 8601 (Monday start, week 1 contains January 4).
Yes, when grouping or filtering by week. Always pair $week with $year in the _id of a $group stage so week numbers from different years do not merge into one bucket.
$week 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 $where for JavaScript-based filtering, or review $isoWeek for ISO calendar weeks.

Next: $where →

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