How to convert a data type from a string to a date?

enter image description here

I am loading data from a csv file into MongoDB. It takes OrderDate as a string data type, which causes problems when creating reports using the BI tool. I have about 10,000 entries in my collection.

Can someone help me how can I change the OrderDate to Date data type with a single query?

+7
source share
2 answers

I do not think you can change the type of a field with a single query. The easiest way is to convert the data rows to Date format using the ISODate function during insertion. But if you want to process the data that you have already inserted, you can do this with the following code using the mongodb console:

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

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

+15
source
 db.messages.find().forEach(function(doc) { doc.headers.datestamp = new Date(Date.parse(doc.headers.Date.toString())); db.messages.save(doc); }) 

It worked to convert a text like this: Tue, Nov 14, 2007 03:22:00 AM -0800 (PST)

Text from an email archive known as Enron Corpus.

0
source

All Articles