Mongodb modifies the field type. Now one of the fields in the collection is string. How to change it to date type?

  mongodb, question

Mongodb modifies the field type. Now one of the fields in the collection is string. How to change it to date type?

MongoDB is “modeless” and there is no concept of metadata for fields, so there is no way to directly modify the field type, because each document’s field has its own type. Based on this situation, only all documents can be traversed to modify the field types one by one. For example, the original document is:

{_id: ObjectId(...), date: "Fri May 20 2016 17:04:27 GMT+0800 (CST)"}

Then you need to traverse the collection to modify the field types one by one

db.coll.forEach(function(doc) {
 db.coll.update({_id: doc._id}, {$set: {date: new Date(doc.date)}});
 });