'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.
Solution 1:[1]
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"
Solution 2:[2]
perhaps simply convert a date into string? this has less to do with mongo than js. moment is awesome but unusable in a 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}});
})
Solution 3:[3]
I just came across this issue. There isn't anything built into ISODate turns out. So I'm converting the ISODate to JSON text, and then I do a substring to get the part I want. You can also use method on ISODate to get year, month, date separately and then combine them.
function formatDate(isoDate){
return isoDate.toJSON().substr(9, 20);
}
Solution 4:[4]
I assume that what you need is the dateToString function https://docs.mongodb.com/manual/reference/operator/aggregation/dateToString/
Solution 5:[5]
If you have mixed data types[string & ISODate()] in an attribute & still want to normalize them to one data type e.g., 'string' then
typeof attr_val === 'string' ? attr_val : attr_val.toJSON()
References:
- @manu answer
- Typechecking
- typeof
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Manu |
Solution 2 | Shubham Chadokar |
Solution 3 | cjmling |
Solution 4 | user2944582 |
Solution 5 |