Text | How Do I Convert A Property In MongoDB From Text To Date Type?

In this post, we will learn How to convert a property in MongoDB from Text to date type we use to date operator in an aggregation of the pipeline.

text

Conversion of Text Into Date Type

To learn more about executing the same in your project follow the steps and code given below to understand the same. Let’s have a collection with the name as myCollection which ave documents that look as follows.

{
  "_id": ObjectId(" 61e147b73f6b2960d12a354c"),
  "dateString": "2022-03-24"
}

And to know the properties of the date String variable text into date format we simply need to follow the code given below and execute it for making this conversion.

db.myCollection.aggregate([
  {
    $addFields: {
      "date": { $toDate: "$dateString" }
    }
  },
  {
    $out: "myCollection"
  }
])

Here we are simply adding another new field as the date to each document which is nothing but a converted date from the dateS String field and the out stage overwrites the existing collection with slight changes in the documents. For more information after executions, the same documents of the whole collection will look different, and to so the result we have given the output below to understand more it.

{
  "_id": ObjectId(" 61e147b73f6b2960d12a354c"),
  "dateString": "2022-03-24",
  "date": ISODate("2022-03-24T00:00:00Z")
}

But here the change in this and above is as same input and output where previously the date String was only a string but here we also have a date field which contained nothing but the date of the date string in string format.

As there is always a different way to do the same thing so in this case also we have another way to do the same which is using the to-date operator but with a constraint and that is it is available only in the latest versions of python which are the latest by python 4.0 and latest to that.

And to execute or implement the same we have given the code to execute and as an example, we have given below where we can learn more and get it done as we want.

db.myCollection.updateMany({}, {$set: {dateAsDate: {$toDate: "$dateAsString"}}})

It will also create a new field of date as the date in all the documents of my collection where my collection is the name of the collection we are using here.

 

To learn more about How to convert a property in MongoDB from text to date type visit: Conversion Text to date format.

To learn more about MongoDB solutions to different problems faced in MongoDB along with concepts and tutorials one different topic visit: MongoDB Problems And Tutorials.

To learn more and explore more about different other programming languages their solutions, tutorials, and concepts posted to get the solutions to the problems faced during solving the problems visit beta python programming languages Solutions.

Leave a Comment

%d bloggers like this: