Date Conversion

Hi ,

I would like to know how to convert my date which is in string format (yyyymmdd) to date format yyyy-mm-dd. How this can be achieved .

Hey Arjun,

If you mean querying and output the date in that format you can apply:

If you mean to update all documents so that they all get the new format instead? In my opinion that’s better handled with a database migration outside of Mongo DB so that you can version control it.

Welcome to the community, @Arjun_Dasari

Can you clarify what you mean by “convert”? Do you want to update all your documents to change how the date fields is stored now (something that can be done inside the database IMO) or do you just want to change how it’s returned when the document is returned to the client or do you want to convert it for purposes of comparison or something else?

Also, dates in MongoDB are full date-time so when you say “yyyy-mm-dd” format that still looks like a string to me and not an ISODate type.


1 Like

Hi @Asya_Kamsky ,

I am looking output format like yyyy-mm-dd . I am exporting the data into CSV format but I am having date format as yyyymmdd in mongoDB . So while exporting the data into CSV i am looking for yyyy-mm-dd format.

Ah, then it’s just a string format change. If you start with string "d" that’s “20211101” and want to end up with “2021-11-01” then this expression will do it:

{$concat:[ {$substr:["$d", 0, 4]}, "-", {$substr:["$d", 4, 2]}, "-", {$substr:["$d", 6, 2]} ]}