Introduction to MongoDB $toDate Operator

In MongoDB, the $toDate operator is used to convert a specified value to a date type. If the specified value cannot be converted to a date type, null will be returned.

Syntax

The syntax of the $toDate operator is as follows:

{
  $toDate: expression
}

Where expression can be any valid expression.

Use Cases

The $toDate operator can be used in the following scenarios:

  • Converting string type dates to date types
  • Converting integer type timestamps to date types

Example

Assume we have a document containing a string type date as follows:

{
  "date": "2022-03-05T14:30:00Z"
}

Now, if we want to convert this date to a date type, we can use the $toDate operator as follows:

db.collection.aggregate([
  {
    $project: {
      convertedDate: { $toDate: "$date" }
    }
  }
])

After executing the above aggregation operation, we will get the following result:

{
  "convertedDate": ISODate("2022-03-05T14:30:00Z")
}

Conclusion

The $toDate operator is a convenient way to convert a specified value to a date type in MongoDB, and can be used to convert string type dates or integer type timestamps to date types. However, it should be noted that if the specified value cannot be converted to a date type, null will be returned.