Introduction to MongoDB $dayOfWeek Operator

$dayOfWeek is an aggregation operator in MongoDB used to extract the day of the week information from a date value. It returns an integer value representing the day of the week, ranging from 1 (Sunday) to 7 (Saturday).

Syntax

The syntax of the $dayOfWeek operator is as follows:

{ $dayOfWeek: <dateExpression> }

Here, <dateExpression> represents a date expression, which can be a field reference, date literal, or any other expression.

Use cases

The $dayOfWeek operator is typically used in aggregation operations to group, sort, filter, and perform other operations on documents containing date fields. For example, we can use the $dayOfWeek operator to count the number of orders, sales, etc. for each day of the week during a given time period.

Example

Suppose we have a collection called “orders” containing information on multiple orders, including order IDs, order dates, etc. Now, we need to count the number of orders for each day of the week and sort them by the count in descending order.

Assuming the “orders” collection contains the following documents:

{ "order_id": 1, "order_date": ISODate("2022-02-28T10:30:00Z") }
{ "order_id": 2, "order_date": ISODate("2022-03-01T11:30:00Z") }
{ "order_id": 3, "order_date": ISODate("2022-03-03T15:30:00Z") }
{ "order_id": 4, "order_date": ISODate("2022-03-04T18:30:00Z") }
{ "order_id": 5, "order_date": ISODate("2022-03-05T09:30:00Z") }
{ "order_id": 6, "order_date": ISODate("2022-03-05T14:30:00Z") }

We can use the following aggregation operation to achieve this:

db.orders.aggregate([
  {
    $group: {
      _id: { $dayOfWeek: "$order_date" },
      count: { $sum: 1 }
    }
  },
  {
    $sort: { count: -1 }
  }
])

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

{ "_id": 7, "count": 2 }
{ "_id": 5, "count": 2 }
{ "_id": 6, "count": 1 }
{ "_id": 2, "count": 1 }

This result indicates that Saturday and Sunday are the two days with the most orders, with 2 orders each. Friday and Tuesday each have 1 order.

Conclusion

The $dayOfWeek operator can be used to convert a date into the corresponding day of the week and count the occurrence of each day of the week in aggregation operations. This is very useful when analyzing documents containing dates. Note that the $dayOfWeek operator returns a number, where 1 represents Sunday, 2 represents Monday, and so on, up to 7 representing Saturday.