MongoDB $dateToParts

In MongoDB, the $dateToParts aggregation pipeline operator returns the date parts of a given date.

More specifically, it returns a document that contains the constituent parts of a given BSON Date value as individual properties.

The date parts returned by $dateToParts are year, month, day, hour, minute, second and millisecond.

When using the $dateToParts operator, you can optionally specify a timezone to use for the result.

The $dateToParts operator accepts either a date (as either a Date, a Timestamp, or an ObjectId), or a document that specifies the date and timezone to use.

Example

Suppose we have a collection called pets with the following document:

{
	"_id" : ObjectId("600631c7c8eb4369cf6ad9c8"),
	"name" : "Fetch",
	"born" : ISODate("2020-12-31T23:30:15.123Z")
}

We can run the following code to return the various date parts from the born field in that document.

db.pets.aggregate(
  [
    {
      $project:
        {
          _id: 0,
          dateParts: { $dateToParts: { date: "$born" } }
        }
    }
  ]
).pretty()

Result:

{
	"dateParts" : {
		"year" : 2020,
		"month" : 12,
		"day" : 31,
		"hour" : 23,
		"minute" : 30,
		"second" : 15,
		"millisecond" : 123
	}
}

We can see that each date part is returned in its own field.

Here, I used dateParts as the field name to return, but this could have been anything (such as theDate etc).

The _id field is returned by default when using projections in MongoDB, but in this example I explicitly hid the _id field using _id: 0.

Specify a Timezone

You can specify a timezone to use for the output of the $dateToParts operator.

When you do this, the argument passed to $dateToParts must be of the following form:

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

Where <dateExpression> is the date to use, and <tzExpression> is the timezone to use.

The timezone can be specified using either the Olson timezone identifier (e.g. "Europe/London", "GMT") or the UTC offset (e.g. "+02:30", "-1030").

Olson Timezone Identifier

Here’s an example that outputs the date parts in two different timezones, each using the Olson timezone IDs:

db.pets.aggregate(
  [
    {
      $project: {
          _id: 0,
          honolulu: { 
            $dateToParts: { date: "$born", timezone: "Pacific/Honolulu" }
            },
          auckland: { 
            $dateToParts: { date: "$born", timezone: "Pacific/Auckland" }
            }
        }
    }
  ]
).pretty()

Result:

{
	"honolulu" : {
		"year" : 2020,
		"month" : 12,
		"day" : 31,
		"hour" : 13,
		"minute" : 30,
		"second" : 15,
		"millisecond" : 123
	},
	"auckland" : {
		"year" : 2021,
		"month" : 1,
		"day" : 1,
		"hour" : 12,
		"minute" : 30,
		"second" : 15,
		"millisecond" : 123
	}
}

In this case, the date moves forward to the next year/month/week/day/hour when using the Pacific/Auckland timezone.

UTC Offset

Here’s the same example, except this time we use the UTC offset.

db.pets.aggregate(
  [
    {
      $project: {
          _id: 0,
          "utcOffset-1000": { 
            $dateToParts: { date: "$born", timezone: "-1000" }
            },
          "utcOffset+1200": { 
            $dateToParts: { date: "$born", timezone: "+1200" }
            }
        }
    }
  ]
).pretty()

Result:

{
	"utcOffset-1000" : {
		"year" : 2020,
		"month" : 12,
		"day" : 31,
		"hour" : 13,
		"minute" : 30,
		"second" : 15,
		"millisecond" : 123
	},
	"utcOffset+1200" : {
		"year" : 2021,
		"month" : 1,
		"day" : 1,
		"hour" : 11,
		"minute" : 30,
		"second" : 15,
		"millisecond" : 123
	}
}

ISO Week Date Parts

You can use iso8601: true to modify the output document to use ISO week date fields. This bases the date on the ISO 8601 standard.

Suppose we have a collection called cats with the following document:

{
	"_id" : ObjectId("6008c9a5c8eb4369cf6ad9cc"),
	"name" : "Scratch",
	"born" : ISODate("2021-01-03T23:30:15.123Z")
}

We can run the following code to extract the ISO date fields from the born field in that document.

Here’s an example to demonstrate:

db.pets.aggregate(
  [
    {
      $project: {
          _id: 0,
          dateParts: { 
            $dateToParts: { 
              date: "$born"
            }
          },
          datePartsISO: { 
            $dateToParts: { 
              date: "$born",
              iso8601: true
            }
          }
      }
    }
  ]
).pretty()

Result:

{
	"dateParts" : {
		"year" : 2020,
		"month" : 12,
		"day" : 31,
		"hour" : 23,
		"minute" : 30,
		"second" : 15,
		"millisecond" : 123
	},
	"datePartsISO" : {
		"isoWeekYear" : 2020,
		"isoWeek" : 53,
		"isoDayOfWeek" : 4,
		"hour" : 23,
		"minute" : 30,
		"second" : 15,
		"millisecond" : 123
	}
}

The first output document uses the normal date output. The second document uses the ISO week date fields and values.

Return the Date Parts from an ObjectId

You can use $dateToParts to return the date parts from an ObjectId.

ObjectId values are 12 byte hexadecimal values that consist of:

  • A 4 byte timestamp value, representing the ObjectId’s creation, measured in seconds since the Unix epoch.
  • A 5 byte is a random value
  • A 3 byte incrementing counter, initialised to a random value.

To recap, our document looks like this:

{
	"_id" : ObjectId("600631c7c8eb4369cf6ad9c8"),
	"name" : "Fetch",
	"born" : ISODate("2020-12-31T23:30:15.123Z")
}

This document contains an ObjectId. We can therefore use $dateToParts to return the date parts, based on the date that our document was created (or more specifically, when the _id field’s ObjectId value was created).

Example:

db.pets.aggregate(
  [
    {
      $project:
        {
          "timeStamp": { $toDate: "$_id"},
          "dateParts": { $dateToParts: { date: "$_id" } }
        }
    }
  ]
).pretty()

Result:

{
	"_id" : ObjectId("600631c7c8eb4369cf6ad9c8"),
	"timeStamp" : ISODate("2021-01-19T01:11:35Z"),
	"dateParts" : {
		"year" : 2021,
		"month" : 1,
		"day" : 19,
		"hour" : 1,
		"minute" : 11,
		"second" : 35,
		"millisecond" : 0
	}
}

In this case, I also used the $toDate aggregation pipeline operator to return the timestamp portion of the ObjectId.