Introduction to MongoDB $isoDayOfWeek Operator

The MongoDB $isoDayOfWeek operator is an aggregation operator used to extract the day of the week in ISO standard from a date-time value. In MongoDB, aggregation operators are widely used to perform data aggregation operations on document collections.

Syntax

The syntax of the $isoDayOfWeek operator is as follows:

{ $isoDayOfWeek: <dateExpression> }

Here, <dateExpression> represents an expression that can be a date object, a date string, or an expression that can be converted to a date.

Use Cases

The $isoDayOfWeek operator is typically used in aggregation queries to group, filter, and calculate fields of time type. For example, the $isoDayOfWeek operator can be used to find data on a specific day of the week or to aggregate statistics by day of the week.

Examples

Here is an example of using the $isoDayOfWeek operator. Suppose we have a sales collection, where each document contains a sale_date field representing the sale date:

{ "_id" : 1, "sale_date" : ISODate("2022-03-01T09:23:12.374Z"), "amount" : 100 }
{ "_id" : 2, "sale_date" : ISODate("2022-03-02T10:34:56.789Z"), "amount" : 200 }
{ "_id" : 3, "sale_date" : ISODate("2022-03-03T11:45:23.456Z"), "amount" : 150 }
{ "_id" : 4, "sale_date" : ISODate("2022-03-04T12:56:34.567Z"), "amount" : 180 }

To calculate the total sales amount for each day of the week, we can use the following aggregation query:

db.sales.aggregate([
  {
    $group: {
      _id: { $isoDayOfWeek: "$sale_date" },
      total_amount: { $sum: "$amount" }
    }
  }
])

The above aggregation query will result in the following output:

{ "_id" : 2, "total_amount" : 100 }
{ "_id" : 3, "total_amount" : 200 }
{ "_id" : 4, "total_amount" : 150 }
{ "_id" : 5, "total_amount" : 180 }

The above result shows the total sales amount for Tuesday, Wednesday, Thursday, and Friday is 100, 200, 150, and 180, respectively.

Conclusion

The $isoDayOfWeek operator is an aggregation operator in MongoDB used to extract the day of the week in ISO standard from a date-time value. It is typically used in aggregation queries to group, filter, and calculate fields of time type. The above example shows how to use and the effect of the $isoDayOfWeek operator.