Skip to content
Advertisement

Updating a pre-exiting fields datatype(string=> date) in a mongoDb collection

I am trying to update a field that was initially captured as a string instead of a date type. Currently, the query that insert into the collection has been modified , so that future insert to that field is date. data type

However, I am trying to update the previously inserted data, before query modification that still has the string data type

Here is what I tried, but giving error

db.collection.update_one({“clusterTime”:{"$type":“string”}},{"$set":{“clusterTime:datetime.datetime.strptime(’$clusterTime’,’%y-%m-%d’).date()}})

I really would appreciate contributions.

Thank you.

Advertisement

Answer

Loop over the records using forEach, convert to date, and save the document

db.collectionName.find({ 'clusterTime' : { '$type' : 'string' }} ).forEach(function (doc) {   
  doc.clusterTime = new Date(doc.clusterTime); // convert field to date
  db.collectionName.save(doc);
});
Advertisement