Introduction to MongoDB $isoWeekYear Operator

In MongoDB, $isoWeekYear is an aggregation operator used to retrieve the year of an ISO week date. This operator returns the ISO week year of a date, which differs from the Gregorian calendar year in that the ISO week year is calculated based on weeks, and the first week of each year must have at least 4 days. If the first week of a year has less than 4 days, it is considered as the last week of the previous year.


The syntax of the $isoWeekYear operator is as follows:

{ $isoWeekYear: <dateExpression> }

Here, dateExpression represents the date expression to be computed, which can be any expression that returns a date.

Use cases

The $isoWeekYear operator is typically used in aggregation operations to compute data for a specific time period. For example, you can use the $isoWeekYear operator to compute the sales amount for each week in a given year.


Suppose you have a sales collection containing the following documents:

{ "_id": 1, "date": ISODate("2022-02-25T10:10:00Z"), "amount": 100 }
{ "_id": 2, "date": ISODate("2022-02-27T14:20:00Z"), "amount": 200 }
{ "_id": 3, "date": ISODate("2022-03-01T09:30:00Z"), "amount": 150 }
{ "_id": 4, "date": ISODate("2023-01-02T16:40:00Z"), "amount": 300 }

You can use the following aggregation operation with the $isoWeekYear operator to compute the ISO week year of each sale and the total sales amount for each week:

    $group: {
      _id: {
        weekYear: { $isoWeekYear: "$date" },
        week: { $week: "$date" }
      totalAmount: { $sum: "$amount" }

After executing the above aggregation operation, the following results will be returned:

{ "_id": { "weekYear": 2022, "week": 8 }, "totalAmount": 300 }
{ "_id": { "weekYear": 2022, "week": 9 }, "totalAmount": 150 }
{ "_id": { "weekYear": 2023, "week": 1 }, "totalAmount": 300 }


The $isoWeekYear operator can be used to easily retrieve the ISO week year of a date for computing data for a specific time period. In aggregation operations, you can combine the $isoWeekYear operator with other operators, such as the $week operator, to perform more detailed data analysis and computation.