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?
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.
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.
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.
In SQL Server, converting a string to date explicitly can be achieved using CONVERT(). CAST() and PARSE() functions.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With