Introduction to MongoDB $dayOfMonth Operator

The MongoDB $dayOfMonth operator is an aggregation expression used to extract the day of the month (1-31) from a date field. This operator returns an integer.

Syntax

{ $dayOfMonth: <dateExpression> }

Use Case

The MongoDB $dayOfMonth operator is typically used in aggregation operations to extract the day of the month from a date field. It can be used together with other date operators such as the $month, $year, and $hour operators to extract different parts of a date.

Example

Suppose we have a collection called sales containing the sales dates and amounts for each employee. We want to find the total sales for each month and sort them by day of the month.

Here are some example documents:

{ "_id" : 1, "employee" : "John", "saleDate" : ISODate("2022-02-02T08:00:00Z"), "saleAmount" : 100 }
{ "_id" : 2, "employee" : "John", "saleDate" : ISODate("2022-02-10T08:00:00Z"), "saleAmount" : 200 }
{ "_id" : 3, "employee" : "Jane", "saleDate" : ISODate("2022-03-12T08:00:00Z"), "saleAmount" : 150 }
{ "_id" : 4, "employee" : "Jane", "saleDate" : ISODate("2022-03-23T08:00:00Z"), "saleAmount" : 250 }

We can use the $dayOfMonth operator and the $group aggregation operation to calculate the total sales for each month and sort them by day of the month. Here is the corresponding aggregation operation:

db.sales.aggregate([
  {
    $group: {
      _id: {
        month: { $month: "$saleDate" },
        dayOfMonth: { $dayOfMonth: "$saleDate" }
      },
      totalSales: { $sum: "$saleAmount" }
    }
  },
  {
    $sort: { "_id.month": 1, "_id.dayOfMonth": 1 }
  }
])

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

{ "_id" : { "month" : 2, "dayOfMonth" : 2 }, "totalSales" : 100 }
{ "_id" : { "month" : 2, "dayOfMonth" : 10 }, "totalSales" : 200 }
{ "_id" : { "month" : 3, "dayOfMonth" : 12 }, "totalSales" : 150 }
{ "_id" : { "month" : 3, "dayOfMonth" : 23 }, "totalSales" : 250 }

In the above example, the $dayOfMonth operator was used to extract the day of the month from the date field and aggregate the sales for each month. Finally, the results were sorted by month and day of the month.

Conclusion

In this article, we introduced the MongoDB $dayOfMonth operator, which can be used to extract the day of the month from a date. We learned about the syntax and use cases of $dayOfMonth and demonstrated its usage with examples.

In practical applications, the $dayOfMonth operator can help us conveniently extract the day of the month from a date to meet different business needs. Whether performing date calculations in aggregation pipelines or filtering dates in queries, the $dayOfMonth operator is a very useful tool.