How to convert from string to date data type?
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
.
db.messages.find().forEach(function(doc) { doc.headers.datestamp = new Date(Date.parse(doc.headers.Date.toString())); db.messages.save(doc); })
This worked well to convert this sort of text: Tue, 14 Nov 2007 03:22:00 -0800 (PST)
The text is from an email archive known as the Enron Corpus.