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

Hello Guyz,

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.

Hi,
Try this

db.collection.update(
   {
      "clusterTime":{
         "$type":"string"
      }
   },
   [
      {
         "$set":{
            "clusterTime":{
               "$dateFromString":{
                  "dateString":"$clusterTime",
                  "format":"%Y-%m-%d"
               }
            }
         }
      }
   ]
)

Good luck

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.