Introduction to MongoDB $week Operator

In MongoDB, the $week operator can be used to extract the week number from a date field. The week number is a number that represents which week of the year it is. This operator can be used in combination with other date operators such as $year and $dayOfMonth to obtain more specific date information.

Syntax

The syntax of the $week operator is as follows:

{ $week: <dateExpression> }

where <dateExpression> is an expression that can be evaluated to a date and can be a field reference, constant, or expression.

Use cases

The $week operator is useful for scenarios where data needs to be grouped or filtered by week. For example, suppose there is a collection that stores sales data, where each document contains a sales date. The $week operator can be used to calculate the total sales amount for each week in order to analyze sales trends.

Examples

Data Example

Suppose the following sales data is available:

{ "_id": 1, "date": ISODate("2022-01-01T00:00:00Z"), "amount": 100 }
{ "_id": 2, "date": ISODate("2022-01-02T00:00:00Z"), "amount": 200 }
{ "_id": 3, "date": ISODate("2022-01-03T00:00:00Z"), "amount": 300 }
{ "_id": 4, "date": ISODate("2022-01-08T00:00:00Z"), "amount": 400 }
{ "_id": 5, "date": ISODate("2022-01-09T00:00:00Z"), "amount": 500 }

Query Example

To calculate the total sales amount for each week, the following aggregation pipeline can be used:

db.sales.aggregate([
  {
    $group: {
      _id: { $week: "$date" },
      totalAmount: { $sum: "$amount" }
    }
  }
])

This aggregation pipeline first uses the $week operator to extract the week number from each document, then uses the $group stage to group the data by week number and calculate the total sales amount for each week. After executing this aggregation, the following results are returned:

{ "_id": 52, "totalAmount": 600 }
{ "_id": 1, "totalAmount": 1200 }

This indicates that the total sales amount for week 52 is 600 and for week 1 is 1200.

Conclusion

The $week operator can be used to extract the week number from a date field and is useful for scenarios where data needs to be grouped or filtered by week. When used in conjunction with the $group aggregation stage, it can easily calculate data such as total sales amount and order count for each week to better analyze business trends.