$dayOfMonth (aggregation)

Definition

  • $dayOfMonth
  • Returns the day of the month for a date as a number between 1 and 31.

The $dayOfMonth expression has the followingoperator expression syntax:

  1. { $dayOfMonth: <dateExpression> }

Changed in version 3.6.

The argument must be a valid expression that resolves to one of the following:

New in version 3.6.

  1. { date: <dateExpression>, timezone: <tzExpression> }

FieldDescriptiondateThe date to which the operator is applied.<dateExpression> must be a valid expression that resolves to aDate, aTimestamp,or an ObjectID.timezoneOptional. The timezone of the operation result.<tzExpression> must be a valid expression that resolves to a string formatted as eitheran Olson Timezone Identifier or aUTC Offset.If no timezone is provided, the result is displayed in UTC.

FormatExamplesOlson Timezone Identifier

  1. "America/New_York"
  2. "Europe/London"
  3. "GMT"

UTC Offset

  1. +/-[hh]:[mm], e.g. "+04:45"
  2. +/-[hh][mm], e.g. "-0530"
  3. +/-[hh], e.g. "+03"

Behavior

ExampleResult
  1. { $dayOfMonth: new Date("2016-01-01") }
1
  1. { $dayOfMonth: { date: new Date("Jan 7, 2003") } }
7
  1. { $dayOfMonth: { date: new Date("August 14, 2011"), timezone: "America/Chicago"} }
14
  1. { $dayOfMonth: ISODate("1998-11-07T00:00:00Z") }
7
  1. { $dayOfMonth: { date: ISODate("1998-11-07T00:00:00Z"), timezone: "-0400"} }
6
  1. { $dayOfMonth: "March 28, 1976" }
error
  1. { $dayOfMonth: Date("2016-01-01") }
error
  1. { $dayOfMonth: "2009-04-09" }
error

Note

$dayOfMonth cannot take a string as an argument.

Example

Consider a sales collection with the following document:

  1. {
  2. "_id" : 1,
  3. "item" : "abc",
  4. "price" : 10,
  5. "quantity" : 2,
  6. "date" : ISODate("2014-01-01T08:15:39.736Z")
  7. }

The following aggregation uses the $dayOfMonth and otherdate operators to break down the date field:

  1. db.sales.aggregate(
  2. [
  3. {
  4. $project:
  5. {
  6. year: { $year: "$date" },
  7. month: { $month: "$date" },
  8. day: { $dayOfMonth: "$date" },
  9. hour: { $hour: "$date" },
  10. minutes: { $minute: "$date" },
  11. seconds: { $second: "$date" },
  12. milliseconds: { $millisecond: "$date" },
  13. dayOfYear: { $dayOfYear: "$date" },
  14. dayOfWeek: { $dayOfWeek: "$date" },
  15. week: { $week: "$date" }
  16. }
  17. }
  18. ]
  19. )

The operation returns the following result:

  1. {
  2. "_id" : 1,
  3. "year" : 2014,
  4. "month" : 1,
  5. "day" : 1,
  6. "hour" : 8,
  7. "minutes" : 15,
  8. "seconds" : 39,
  9. "milliseconds" : 736,
  10. "dayOfYear" : 1,
  11. "dayOfWeek" : 4,
  12. "week" : 0
  13. }