Mongo date format

Hello @tim_Ran ,

Welcome to The MongoDB Community Forums! :wave:

I notice you haven’t had a response to this topic yet - were you able to find a solution?
If not, I assume you wanted to convert the datatype of the field createdAt from string to ISODate, you can update below query as per your use case.

db.collection.updateMany(
                     {"createdAt": 
                      {$type:"string"}
                     },
                     [{$set: 
                       {"createdAt": 
                         {$toDate : "$createdAt"}
                       }}]
)

Explanation:

  • db.collection.updateMany() will updates all documents that match the specified filter for a collection
  • $type will help check which documents in whole collection have “createdAt” as a String Data type
  • $set operator replaces the value of a field with the specified value.
  • $toDate Converts a value to a date. If the value cannot be converted to a date, $toDate errors. If the value is null or missing, $toDate returns null.

Regards,
Tarun

4 Likes