How to convert from string to date data type?

前端 未结 2 1816
谎友^
谎友^ 2020-12-03 05:55

\"enter

I am uploading data from a csv file to MongoDB. It is taking OrderDate

相关标签:
2条回答
  • 2020-12-03 06:17

    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.

    0 讨论(0)
  • 2020-12-03 06:20
    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.

    0 讨论(0)
提交回复
热议问题