MongoDB

MongoDB $DateFromParts and $DateToParts Operators

The MongoDB $dateFromParts and $dateToParts operators are part of the aggregation method. These operators are used to accomplish the date operation in MongoDB. The $dateFromParts operator creates and returns a document with the Date structure from the constituent parts of the Date in MongoDB. It takes an individual field for each date constituent. While the $dateToParts operator gives a document with individual features for each part of a specified BSON Date value. The date parts that are returned from the $dateToParts operator are passed as parameters inside the $dateFromParts operator.

How Do the $DateFromParts and $DateToParts Work in MongoDB

The use of the $dateFromParts and the $dateToParts operators are demonstrated here to fetch the dates accordingly. We require the collection of MongoDB which is utilized to work with these operators. We give a “ChildBirthDate” collection where the following documents are inserted using the insertion command of MongoDB.

db.ChildBirthDate.insertMany([
      {
          "_id": 1,
          "Birth_Year" : 2021,
      "Birth_Month" : 09,
      "Birth_Day" : 21,
      "Birth_Hour" : 15,
      "Birth_Minute" : 60,
      "Birth_Second" : 31
         
      },
       {
          "_id": 2,
          "Birth_Year" : 2021,
      "Birth_Month" : 09,
      "Birth_Day" : 21,
      "Birth_Hour" : 15,
      "Birth_Minute" : 60,
      "Birth_Second" : 31,
         
      },
   {
         "_id": 3,
          "Birth_Year" : 2023,
      "Birth_Month" : 16,
      "Birth_Day" : 90,
      "Birth_Hour" : 47,
      "Birth_Minute" : 190,
      "Birth_Second" : 697
         
      },
       {
          "_id": 4,
          "Birth_Year" : 2022,
      "Birth_Month" : 0,
      "Birth_Day" : 0,
      "Birth_Hour" : 0,
      "Birth_Minute" : 0,
      "Birth_Second" : 0
         
},
    {
          "_id" : 5,
    "Child_Name" : "Emily",
    "DOB" : ISODate("2023-01-06T22:35:12.130Z")
         
},
   {
          "_id" : 6,
    "Child_Name" : "Kim",
    "DOB" : ISODate("2022-11-05T23:10:16.125Z")
         
}
])

The documents are inserted within the provided collection as shown in the previous output. We can use these documents to query the $dateFromParts and $dateToParts operators. Note that we use over the $dateFromParts operator in the first four documents because the dates in these documents are parted away. Besides that, the $dateToParts operator uses the last two documents since they contain the single date objects.

{
  acknowledged: true,
  insertedIds: { '0': 1, '1': 2, '2': 3, '3': 4, '4': 5, '5': 6 }
}

Example 1: Using the $DateFromParts Operator in MongoDB

The $dateFromParts operator is used here over the first document of the given collection to get the single date object. The “{ _id: 1}” expression is specified to the $match stage. Then, we have the $project stage where the “DateResult” field is inserted to deploy the $dateFromParts operator. The $dateFromParts operator inputs the constituent parameters of the date along with the specified fields of the matched document to give the date object.

db.ChildBirthDate.aggregate([
{ $match: { _id: 1} },
{
   $project: {
      DateResult: {
         $dateFromParts: {
            "year" : "$Birth_Year", "month" : "$Birth_Month", "day": "$Birth_Day", "hour" : "$Birth_Hour"
         }
       }
    }
}
])

The single date is retrieved from all the parts of the dates in the output by the $dateFromParts operator.

[ { _id: 1, DateResult: ISODate("2021-09-21T15:00:00.000Z") } ]

Example 2: Using the $DateFromParts Operator with a Specified Timezone in MongoDB

We can also use the timezone parameter within the $dateFromParts operator to get the date object of a given timezone. We first use the $match operator to match the predefined document which is “{ _id: 2} ”. Then, we invoke the $dateFromParts operator in the “date” field of the $project stage. We use all the date parameters that are needed to get the date object in addition to the “timezone” parameter. The “timezone” is given a timezone of “Europe/London” to get the resultant date in that specified zone.

db.ChildBirthDate.aggregate([
 { $match: { _id: 2} },
{
   $project: {
         date: {
         $dateFromParts: {
            "year" : "$Birth_Year", "month" : "$Birth_Month",
            "day" : "$Birth_Day", "hour" : "$Birth_Hour",
            "minute" : "$Birth_Minute", "second" : "$Birth_Second", "timezone": "Europe/London" }
      }
   }
  }
])

The $dateFromParts operator returns the following date object of the given timezone:

[ { _id: 2, date: ISODate("2021-09-21T15:00:31.000Z") } ]

Example 3: Using the $DateFromParts Operator with a Greater Range of Dates in MongoDB

Here, we get the date object from the second document whose date parts are greater than the range. Within the $dateFromParts operator, we use the constituent parameters to generate a single object of the date from the range that is greater than the specified date values. We set the fields from the documents according to the specified constituent parameters. The $dateFromParts operator increases the year “2023” to “2024” and then sets the month value to “12” to give the single date object from the invalid date values.

db.ChildBirthDate.aggregate([
  { $match: { _id: 3} },
  {
    $project: {
        DateFromParts: {
          $dateFromParts: {
              "year": "$Birth_Year",
              "month": "$Birth_Month",
              "day": "$Birth_Day",
              "hour": "$Birth_Hour",
              "minute": "$Birth_Minute",
              "second": "$Birth_Second"
          }
        }
    }
  }
])

As seen in the output, the date constituents in the returned date object differ from the corresponding date values in the document. The reason is that the date was recalculated by $dateFromParts to take the date parameters into consideration that are outside of the expected range.

[ { _id: 3, DateFromParts: ISODate("2024-07-01T02:21:37.000Z") } ]

Example 4: Using the $DateFromParts Operator with a Range Less Than the Specified Dates in MongoDB

Now, we have another case of the $dateFromParts operator where the date values are less than the valid range of dates. We match the document which contains the date and time fields beyond their respective acceptable ranges. The document whose “_id” is “3” is passed inside the $match stage expression. After that, we create the “DateFromParts” field in the $project stage. The “DateFromParts” field is employed with the $dateFromParts operator. The $dateFromParts operator is passed with its associated parameters to get the date object. Since we have all the values of the date parameters in the matched document that are zero which is less than the minimum values of the date ranges, the $dateFromParts operator resets all the date parameters first to generate the single date object.

db.ChildBirthDate.aggregate([
  { $match: { _id: 4} },
  {
    $project: {
        DateFromParts: {
          $dateFromParts: {
              "year": "$Birth_Year",
              "month": "$Birth_Month",
              "day": "$Birth_Day",
              "hour": "$Birth_Hour",
              "minute": "$Birth_Minute",
              "second": "$Birth_Second"
          }
        }
    }
  }
])

The resultant single ISO date is formed in the following by the $dateFromParts operator which drops the year “2022” by one and limits the month to 12.

[ { _id: 4, DateFromParts: ISODate("2021-11-30T00:00:00.000Z") } ]

Example 5: Using the $DateToParts Operator in MongoDB

Now, we use another $dateToParts operator from which the date parts are obtained. Here, we have a simple demonstration where we match the “_id” whose value is “5” at the initial stage. After matching the document, the $project stage gets the results of the $dateToParts operator in the “DateInParts” field. The $dateToParts operator inputs the “date” parameter which is provided with the “$DOB” field. The $DOB field has the date object which is separated into the date parts by the $dateToParts operator.

db.ChildBirthDate.aggregate(
  [
  { $match: { _id: 5} },
    {
      $project:
        {
          _id: 0,
          DateInParts: { $dateToParts: { date: "$DOB" } }
        }
    }
  ]
)

The $dateToParts operator returns the following date parts from the $DOB field of the matched document:

[
  {
    DateInParts: {
      year: 2023,
      month: 1,
      day: 6,
      hour: 22,
      minute: 35,
      second: 12,
      millisecond: 130
    }
  }
]

Example 6: Using the $DateToParts Operator for ISO Week Date Format in MongoDB

We can use the iso8601 option with the true value to update the returned document to use the ISO week date fields. The date is computed using the ISO 8601 specification. Consider that we modify the document which has the “_id” equal to the value of “5”. In that document, we apply the $dateToParts operator where the “date” parameter is set with the “$DOB” field. The “iso8601” parameter is also given with the value which is set to “true”.

db.ChildBirthDate.aggregate(
  [
 { $match: { _id: 5} },
    {
      $project: {
          _id: 0,
          datePartsISO: {
            $dateToParts: {
              date: "$DOB",
              iso8601: true
            }
          }
      }
    }
  ]
).pretty()

The date parts of that document are obtained from the $dateToParts operator that contains the ISO week field and date values.

[
  {
    datePartsISO: {
      isoWeekYear: 2023,
      isoWeek: 1,
      isoDayOfWeek: 5,
      hour: 22,
      minute: 35,
      second: 12,
      millisecond: 130
    }
  }
]

Conclusion

This article explained the MongoDB aggregation pipeline method terms, $dateFromParts and $dateToParts. The $dateFromParts and $dateToParts operators work oppositely to each other. The $dateFromParts operator gives the ISO format date from the date parts. On the other hand, the $dateToParts takes the ISO format date to return the date parts with the value. We explored these operators with simple and complex cases of examples to clarify the concept of using the $dateFromParts and $dateToParts operators in MongoDB.

About the author

Saeed Raza

Hello geeks! I am here to guide you about your tech-related issues. My expertise revolves around Linux, Databases & Programming. Additionally, I am practicing law in Pakistan. Cheers to all of you.