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.
source to share
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} );
})
source to share
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);
}
source to share
I assume you want dateToString function https://docs.mongodb.com/manual/reference/operator/aggregation/dateToString/
source to share