MongoDB $week Operator

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

What Is $week?

$week is a MongoDB aggregation expression that returns the week of the year for a date as an integer from 0 to 53. Weeks start on Sunday. Week 1 contains the first Sunday of the year; earlier days are week 0.

Remember
$week = week-of-year for aggregation

{ $week: <dateExpression> }

weeks start on Sunday
range → 0 … 53
week 1 → contains first Sunday of the year
days before that → week 0

Always pair with $year for reports
ISO Mondays → use $isoWeek instead
UsePrefer
Sunday-based week number$week
ISO 8601 week (Monday)$isoWeek
Calendar year for grouping$year + $week

How to Use $week in MongoDB

Pass a date field, get a week number, and usually keep the year next to it.

  1. Choose an expression stage ($addFields, $project, or $group).
  2. Pass a date field (or date expression) to $week.
  3. Also extract $year when you group, filter, or label weeks.
  4. Use $isoWeek instead if your reports follow ISO Monday weeks.
PieceRequired?Role
$weekYesDate → week number (0–53)
Date expressionYesField, literal date, or nested date expr
$yearRecommendedDisambiguate the same week across years

Pseudocode

Pseudocode
for each document:
    d = evaluate(dateExpression)
    if d is null or missing:
        result = null
    else:
        result = sundayBasedWeekOfYear(d)   // 0 … 53
    emit { ..., week: result }

Cheat Sheet

Keep these facts handy while building weekly date expressions.

TopicDetail
TypeAggregation expression (not a find filter alone)
Syntax{ $week: <dateExpression> }
Range0 to 53
Week startSunday
Week 1Contains the first Sunday of the year
Group pattern_id: { year: { $year: "$d" }, week: { $week: "$d" } }
Nullnull / missing → null

Live Preview

Watch $week turn a date into a Sunday-based week number. Pick a sample order date.

Simulates MongoDB $week (Sunday start) and shows $year beside it.

Result
date = 2024-06-10 (UTC)

$week → 23
$year → 2024

{ orderWeek: 23, orderYear: 2024 }

Worked Walkthrough — June Order

One order is dated 2024-06-10 (a Monday in UTC). Goal: find its Sunday-based week number.

Calculation
Document:
  { orderDate: ISODate("2024-06-10T12:00:00Z") }

2024-01-01 = Monday → days before first Sunday = week 0
First Sunday of 2024 = 2024-01-07 → start of week 1

Week containing 2024-06-10:
  Sunday of that week = 2024-06-09
  → $week = 23
  → $year = 2024

Same week: 2024-06-15 (Saturday)
Next week: 2024-06-17 → week 24

MongoDB Examples

We use a small orders collection. First extract week and year, then group revenue by year + week. Run these in mongosh after inserting the sample data once.

Example 1 — Sample Data

Imagine three orders in June 2024. Two fall in the same Sunday-based week; one falls in the next week.

mongosh
db.orders.insertMany([
  {
    _id: 1,
    customer: "Alice",
    orderDate: ISODate("2024-06-10T14:30:00Z"),
    amount: 120
  },
  {
    _id: 2,
    customer: "Bob",
    orderDate: ISODate("2024-06-15T09:00:00Z"),
    amount: 85.5
  },
  {
    _id: 3,
    customer: "Carol",
    orderDate: ISODate("2024-06-17T16:45:00Z"),
    amount: 210
  }
]);

How the Data Is Stored in MongoDB

After the insert, MongoDB keeps three documents in orders. Run find() to see them:

mongosh
db.orders.find()

Read each document like this:

Field in MongoDBExamplePlain English
_id1Document id (row number for this lesson)
customer"Alice"Who placed the order
orderDate2024-06-10Order timestamp (BSON Date)
amount120Order total

How It Works

  1. Insert once. insertMany adds three order documents to orders.
  2. Dates are BSON Dates. ISODate(...) stores a real date, not a string.
  3. find() shows the same shape. Ready for $week in the next examples.

Example 2 — Extract Week

Goal: add orderWeek and orderYear for each order so reports are easy to read.

mongosh
db.orders.aggregate([
  {
    $addFields: {
      orderWeek: { $week: "$orderDate" },
      orderYear: { $year: "$orderDate" }
    }
  }
]);

How It Works

  1. Read the stored date. Alice’s orderDate is 2024-06-10 (Monday) from Example 1.
  2. Compute the week. $week returns 23 (Sunday-based week containing June 9–15).
  3. Keep the year. $year returns 2024 so the week label is unambiguous.
  4. Same week check. Bob (June 15) is also week 23; Carol (June 17) moves to week 24.

Example 3 — Group by Week

Same orders, but build a weekly revenue summary. Pair $year and $week in the group key.

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 } }
]);

How It Works

  1. Same stored documents. Still using Alice, Bob, and Carol from Example 1.
  2. Build a unique week key. _id combines year + week so weeks from other years cannot collide.
  3. Aggregate. Alice + Bob land in week 23 (120 + 85.5 = 205.5); Carol is alone in week 24.
  4. Easy check. Week 23 should show orderCount: 2.

Edge Cases & Pitfalls

Check these before using $week in production pipelines.

year

Always pair with $year

Week numbers repeat every year. Group or filter with both $year and $week.

iso

$week ≠ $isoWeek

$week starts Sunday; $isoWeek follows ISO (Monday). The same date can get different numbers.

week0

Week 0 is real

Days before the first Sunday of the year return 0. Do not assume every date is week 1 or higher.

tz

Timezone can shift the week

Near day boundaries, UTC vs local timezone can move a date into the previous or next Sunday week. Pass a timezone when needed.

Performance Notes

ApproachCostBest for
$week alonePer-document date mathLabels / display fields
$year + $week groupConvert + groupWeekly revenue reports
Filter by date range firstFewer docs to convertLarge collections

Date-part extraction is cheap compared with large sorts or joins. Prefer a $match on a date range before grouping by week on big collections.

Key Takeaways

  • Role: date → Sunday-based week number (0–53).
  • Pairing: always keep $year with $week for groups.
  • ISO needs: use $isoWeek for Monday-based weeks.
  • Week 0: days before the first Sunday of the year.

One line: $week answers “which Sunday-based week of the year is this date?”—usually reported with $year.

Frequently Asked Questions

$week returns the week of the year for a BSON Date as an integer from 0 to 53. Use it inside aggregation expression stages such as $project, $addFields, and $group.
Use { $week: <dateExpression> }. Pass a field like "$orderDate", a literal date, or a date expression. You can also pass { date: <dateExpression>, timezone: <tzExpression> }.
Weeks start on Sunday. Week 1 is the week that contains the first Sunday of the year. Days before that Sunday are week 0. This differs from $isoWeek (ISO 8601, Monday start).
Yes when grouping or filtering. Pair $week with $year so week 23 in 2023 and week 23 in 2024 do not merge into one bucket.
$week returns null when the input is null or the field is missing. It does not throw an error for null input.
Use $isoWeek when you need ISO 8601 weeks (Monday start, week 1 contains January 4). Use $week for the Sunday-based MongoDB calendar.

Next: $where

Use a JavaScript expression to filter documents in a query.

$where 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