How can I convert mondodb ISODate to string in mongoDB?

I have ISODate in mongo as ISODate and I want it in string format with specific datetime format.

Here is the ISODate:

ISODate("2020-04-24T11:41:47.280Z")

      

Expected Result:

"2020-04-24T11:41:47.280Z"

      

I only want this to happen on mongodb if many of my services are expected in this format and I don't want to change all the services as a tedious job.

+3


source to share


4 answers


I got the expected result when I tried to do the following.

ISODate("2020-04-24T11:41:47.280Z").toJSON()

      



This will return me the line

"2020-04-24T11:41:47.280Z"

      

+9


source


is it possible to just convert the date to a string? this has less to do with mongo than js. moment awesome but unusable in mongo shell script.



db.events.find().forEach(function(doc) {     
   //   printjson ("Document is " + doc);    
   var isoDate = doc.t;   // t is correct key?     
   var isoString = isoDate.toISOString()    
   // update the collection with string using a new key    
   db.events.update({"_id":doc._id},{$set:{"iso_str":isoString} );
   // or overwrite using 't' key      db.events.update({"_id":doc._id},{$set:{"t":isoString} );
})

      

+1


source


I just came across this problem. Nothing happens in ISODate. So I convert ISODate to JSON text and then create a substring to get the part I want. You can also use the method in ISODate to get the year, month, date separately and then concatenate them.

function formatDate(isoDate){
    return isoDate.toJSON().substr(9, 20);
}

      

0


source


0


source







All Articles