Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert from string to date data type?

enter image description here

I am uploading data from a csv file to MongoDB. It is taking OrderDate as string data type due to which facing problems while creating reports using a BI tool. I have about 10000 records in my collection.

Could anyone help me how can I change the data Type of OrderDate to Date with a single query?

like image 697
divya Avatar asked Mar 18 '13 09:03

divya


People also ask

How do I convert a string to a date?

Using strptime() , date and time in string format can be converted to datetime type. The first parameter is the string and the second is the date time format specifier. One advantage of converting to date format is one can select the month or date or time individually.

How do I change data type from text to date?

Convert a Text to Date But if you look at the cell format, it's text. So here, is the best way to use the DATEVALUE function. You just need to refer to that cell in the function and it will convert that data into an actual date. And, then you can change its format to date.

How do I convert string to date in python?

We can convert a string to datetime using strptime() function. This function is available in datetime and time modules to parse a string to datetime and time objects respectively.

How do I convert a string to a date in SQL?

In SQL Server, converting a string to date explicitly can be achieved using CONVERT(). CAST() and PARSE() functions.


1 Answers

I don't think that you can change field's type with single query. The easiest way is to convert data strings into Date format using ISODate function during the insertion. But, if you want to process the data you already inserted, you can do it with the following code using mongodb console:

db.collection.find().forEach(function(element){
  element.OrderDate = ISODate(element.OrderDate);
  db.collection.save(element);
})

This code will process each element in your collection collection and change the type of Orderdate field from String to Date.

like image 142
Leonid Beschastny Avatar answered Sep 28 '22 15:09

Leonid Beschastny