Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Convert mongodb ISODate to string in mongoDB?

I have my ISODate in mongo as ISODate and I want to just that in string format with a specific datetime format.

Here is the ISODate:

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

Expected Result:

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

I want this to be happened on mongodb only as many of my services are expecting in this format, and I don't want to make changes in all services as its a tedious job.

like image 837
Manu Avatar asked Dec 19 '14 05:12

Manu


People also ask

What is ISODate in MongoDB?

You can specify a particular date by passing an ISO-8601 date string with a year within the inclusive range 0 through 9999 to the new Date() constructor or the ISODate() function. These functions accept the following formats: new Date("<YYYY-mm-dd>") returns the ISODate with the specified date.

How do I change the date format in aggregation in MongoDB?

If you have documents that store dates as Date objects, but you want to return them in a different format, you can use the $dateToString aggregate pipeline operator. The $dateToString operator converts the Date object to a string, and optionally allows you to specify a format for the resulting output.

How do I get the current date in MongoDB?

The Date () method returns the date as a string or a Date object. In MongoDB shell or mongosh, the Date () method returns the current date as a string. The new Date () function returns a Date object with the current date. The ISODate helper is wrapped around the Date object by mongosh, and the ISODate is in UTC (Universal Time).

How to define a specific date using mongosh?

The new Date () function returns a Date object with the current date. The ISODate helper is wrapped around the Date object by mongosh, and the ISODate is in UTC (Universal Time). You can use the new Date () function or the ISODate () method to define a specific date by giving an ISO-8601 date string with a year between '0' and '9999'.

What does $convert return in MongoDB?

If unspecified, $convert returns null if the input is null or missing. In addition to $convert, MongoDB provides the following aggregation operators as shorthand when the default "onError" and "onNull" behavior is acceptable: The following table lists the input types that can be converted to a boolean:

How do I use the isodate helper with Date object?

The ISODate helper is wrapped around the Date object by mongosh, and the ISODate is in UTC (Universal Time). You can use the new Date () function or the ISODate () method to define a specific date by giving an ISO-8601 date string with a year between '0' and '9999'.


1 Answers

I got the expected result while i was trying the following.

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

This will give me back the string

"2020-04-24T11:41:47.280Z"
like image 57
Manu Avatar answered Sep 17 '22 20:09

Manu