This article contains a list of date operators, methods, and variables that you can use when working with dates in MongoDB.
Field Update Operators
Operator | Description |
---|---|
$currentDate | Sets the value of a field to the current date. It can be set as either a Date or a timestamp type. The default is Date. |
Date Expression Operators (Aggregation Pipeline)
The following aggregation pipeline operators return date objects or components of a date object. These can be used to construct expressions for use in the aggregation pipeline stages.
Operator | Description |
---|---|
$dateFromParts | Constructs a BSON Date object from the date’s constituent parts. |
$dateFromString | Converts a date/time string to a date object. |
$dateToParts | Returns a document containing the constituent parts of a date. |
$dateToString | Returns the date as a string. |
$dayOfMonth | Returns the day of the month for a given date as a number between 1 and 31 . |
$dayOfWeek | Returns the day of the week for a given date as a number between 1 (Sunday) and 7 (Saturday). |
$dayOfYear | Returns the day of the year for a given date as a number between 1 and 366 (leap year). |
$hour | Returns the hour for a given date as a number between 0 and 23 . |
$isoDayOfWeek | Returns the weekday number of a given date in ISO 8601 format, ranging from 1 (for Monday) to 7 (for Sunday). |
$isoWeek | Returns the week number of a given date in ISO 8601 format, ranging from 1 to 53 . |
$isoWeekYear | Returns the year number for a given date in ISO 8601 format. |
$millisecond | Returns the milliseconds of a given date as a number between 0 and 999 . |
$minute | Returns the minute for a given date as a number between 0 and 59 . |
$month | Returns the month for a given date as a number between 1 (January) and 12 (December). |
$second | Returns the seconds for a given date as a number between 0 and 60 (leap seconds). |
$toDate | Converts a value to a Date. |
$week | Returns the week number for a given date as a number between 0 (the partial week that precedes the first Sunday of the year) and 53 (leap year). |
$year | Returns the year for a given date as a number (e.g. 2021 ). |
Methods
The following method can be used to return either a date/time string or a Date object.
Method | Description |
---|---|
Date() | Returns either a date/time string or a Date object. You can provide a date. If you don’t , it will return the current date/time. |
System Variables
The following system variables can be used to return a datetime or timestamp value when using an aggregation pipeline.
Method | Description |
---|---|
NOW | Returns the current datetime value. This variable was introduced in MongoDB version 4.2. |
CLUSTER_TIME | Returns the current timestamp value. Only available on replica sets and sharded clusters. This variable was introduced in MongoDB version 4.2. |