Introduction to MongoDB $dayOfYear Operator

The $dayOfYear operator is one of the date operators in MongoDB’s aggregation pipeline. It is used to extract the day of the year from a date. The $dayOfYear operator can be used to convert a date to its day of the year, which can then be used for aggregation.

Syntax

The syntax of the $dayOfYear operator is as follows:

{ $dayOfYear: <dateExpression> }

Here, <dateExpression> is an expression that represents a date, which can be a date object, a date string, or another expression that returns a value representing a date, such as the $toDate operator.

Use Cases

The $dayOfYear operator is useful for extracting the day of the year from a date, which can then be used for aggregation. For example, it can be used to calculate the number or sum of events within a certain time period in a year.

Examples

Suppose we have a collection called sales that contains information about multiple sales records, including the sales date and amount. Now, we want to group the sales records by the day of the year and calculate the total sales amount for each group.

Suppose the sales collection contains the following documents:

{ "_id": 1, "date": ISODate("2022-01-01"), "amount": 100 }
{ "_id": 2, "date": ISODate("2022-01-02"), "amount": 200 }
{ "_id": 3, "date": ISODate("2022-01-03"), "amount": 150 }
{ "_id": 4, "date": ISODate("2022-02-01"), "amount": 300 }
{ "_id": 5, "date": ISODate("2022-02-02"), "amount": 250 }
{ "_id": 6, "date": ISODate("2022-02-03"), "amount": 400 }

We can use the $dayOfYear operator to get the day of the year for each sales record’s date, and then use the $group aggregation operation to group the sales records by day of the year and calculate the total sales amount for each group. Here’s how to do it:

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

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

{ "_id": 1, "totalAmount": 450 }
{ "_id": 32, "totalAmount": 950 }

The results show that the total sales amount for January 1st, 2nd, and 3rd is 450, and for February 1st, 2nd, and 3rd is 950.

Conclusion

The $dayOfYear operator can be used to get the day of the year for a date and can be used in conjunction with other aggregation operations. By grouping the dates and calculating the value of each group using the $sum operator, we can easily perform aggregation analysis for a certain time period in a year.