| by Arround The Web | No comments

MongoDB $DateFromStrings Operator

The aggregation pipeline $dateFromString operator of MongoDB changes a date/time string into a date object. The $dateFromString must be provided with the dateString argument where the date value is assigned to be transformed. The $dateFromString operator also includes the timezone, format, onError, and OnNull parameters which are optional. It also includes a few extra features as well such as the ability to customize the format of the date and timezone. Thus, with the $dateFromString, we can convert the string-type dates into the date object.

How the $DateFromString Operator Works in MongoDB

The use of the $dateFromString operator in MongoDB is to convert the string form of a date into the date object. Here, we convert the string date of the documents which are specified in the MongoDB collection. We generate the “DateSheet” collection within the MongoDB shell where we follow the following query to insert some documents inside it. These documents are inserted with the field which contains the string date.

db.DateSheet.insertMany([
      {
          "_id": 1,
          "Date": "2023-04-30",
          "timezone": "America/New_York"
      },
       {
          "_id": 2,
          "Date": "1-5-2021",
          timezone: "UTC"
      },
       {
          "_id": 3,
          "Date": "10/02/2021",
          "timezone": "America/New_York"
      },
       {
          "_id": 4,
          "Date": null,
          "timezone": "UTC"
      },
       {
          "_id": 5,
          "Date": "20211-03-05T04:35:01.066",
          "timezone": "GMT"
      }

  ])

Now, the query of inserting the documents shows that the documents are stored successfully in the “DateSheet” collection. We can use it over the $dateFromString operator where the field with the string date is converted into the date object of MongoDB.

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

Example 1: Using the MongoDB $DateFromString Operator to Get the Date Object

The $dateFromString is deployed for the transformation of the specified date into the date object. We have given a document to which we want this transformation. The document is given as the “{ _id: 1 }” expression to the $match stage. First, the document with the “_id” value which is stored as “1” is matched within the “DateSheet” collection. Then, the $project operator is performed. The $project operator is set with the “DateObject” attribute where the $dateFromString operator is called for the date transformation operation.

The $dateFromString operator is passed with the “dateString” argument where the “$Date” field is defined that needs to be transformed into a date object. After that, we pass the “timezone” argument to the $dateFromString operator with a time zone of “America/New_York”.

db.DateSheet.aggregate( [
{ $match: { _id: 1 } },
{
   $project: {
      DateObject: {
         $dateFromString: {
            dateString: '$Date',
            timezone: 'America/New_York'
         }
      }
   }
} ] )

The aforementioned $dateFromString operator returns the following results where each date field is changed to American DateTime:

[ { _id: 1, DateObject: ISODate("2023-04-30T04:00:00.000Z") } ]

Example 2: Using the MongoDB $DateFromString Operator with the OnError Parameter

The $dateFromString operator throws an error if your collection contains documents with date strings that cannot be parsed unless we pass an aggregation statement to the additional onError parameter. The invalid date is returned in its original string value through the onError parameter. We have a document with the “_id” value of “5” whose $Date field provides the invalid date values. We match that document first with the $match stage. After that, we use the $project operator to call the operation of the $dateFromString operator. The $dateFromString operator is defined with the “dateString ” input parameter where the $Date field is assigned.

Next, we define the timezone parameter with the eastern time. Then, the “onError ” parameter is set with the error message which is generated when the $dateFromstring encounters the error while transforming the string date into the date object.

db.DateSheet.aggregate( [
 { $match: { _id: 5 } },
{
   $project: {
      DateObject: {
         $dateFromString: {
            dateString: '$Date',
            timezone: 'America/New_York',
            onError: "An exception occurred while parsing the string date"
         }
      }
   }
} ] )

Since the “20211-03-05T04:35:01.066” string date is not valid, the MongoDB server generates the error message set within the onError parameter.

[
  {
    _id: 5,
    DateObject: 'An exception occurred while parsing the string date'
  }
]

Example 3: Using the MongoDB $DateFromString with the OnNull Parameter

When null is placed against the date field, we can require the $dateFromString to provide a date that corresponds to the Unix epoch rather than null from the onNull argument. Any valid expression can be utilized as the value for the onNull argument. Here, we have a document having the date field as “null”. The $match stage matches the document to be parsed by the $dateFromString operator. We assign the “$Date” date field in the “dateString” argument and also the timezone parameter with the $timezone field to the $dateFromString operator. After that, we have the onNull parameter which assigns a new Date(0) to return the epoch date object.

db.DateSheet.aggregate( [
{ $match: { _id: 4 } },
 {
   $project: {
      date: {
         $dateFromString: {
            dateString: '$Date',
            timezone: '$timezone',
            onNull: new Date(0)
         }
      }
   }
} ] )

Since the date is not set in the document and contains the null value, the resultant parsed date that is returned by the previous query has elapsed since January 1, 1970.

[ { _id: 4, date: ISODate("1970-01-01T00:00:00.000Z") } ]

Example 4: Using the MongoDB $DateFromString Operator with the Format Parameter

We can customize the format using the optional format argument of the $dateFromString operator for the provided date/time string. The default format of the date object is “%Y-%m-%dT%H:%M:%S.%Lz” which is returned by the $dateFromString operator in the prior examples. We transform the document which is specified to the $match stage. The document has the string date value of “10/02/2021” where the 10th value can be the date or a month. Likewise, the “02” value in the specified date can be the date or a month.

For this, we set the “format” parameter in the $dateFromString operator. To precisely specify which one, the “format” option is used in the “%m/%d/%Y” format. The $dateFromString operator parses the specified date of the document into the date object in the given format specification.

db.DateSheet.aggregate([
  { $match: { _id: 3 } },
  {
    $project: {
        date: {
          $dateFromString: {
              dateString: '$Date',
              format: "%m/%d/%Y"
          }
        }
    }
  }
])

The string date is parsed into the date object of the specified format.

[ { _id: 3, date: ISODate("2021-10-02T00:00:00.000Z") } ]

Example 5: Using the MongoDB $DateFromString Operator to Get the Date Object in ISO Week Format

We can also express the dates in ISO 8601 format with a few different format specifiers. We use the document of “_id” equal to “2” to get the parsed date object in the ISO week format. We set the specification of the format parameter as “%u-%V-%G” within the $dateFromString operator. The “u” denotes the year, “V” indicates the days in the week, and “G” represents the year of the week in ISO 8601 format.

db.DateSheet.aggregate([
  { $match: { _id: 2 } },
  {
    $project: {
        date: {
          $dateFromString: {
              dateString: '$Date',
              format: "%u-%V-%G"
          }
        }
    }
  }
])

The “1-5-2021” string date of the matched document is parsed into the ISO week format date as shown in the following:

[ { _id: 2, date: ISODate("2021-02-01T00:00:00.000Z") } ]

Conclusion

This article contains all the informative knowledge regarding the $dateFromString operator of MongoDB. We used the $dateFromString operator to parse the string format date into the date object. The $dateFromOperator is used here along with its optional parameter to explore the working of these parameters to transform the value of the string date. Furthermore, we employed the $dateFromString to transform the string into the given format specifications.

Share Button

Source: linuxhint.com

Leave a Reply