I want to format the date time into an specific format on the mongo shell output
My query
db.getCollection('people').find({
date: {
$gte: ISODate("2017-04-24T14:04:34.447Z")
}
},
{
_id: 0,
age: 0,
}
);
My output against this query:
/* 1 */
{
"user_id" : "bcd020",
"status" : "D",
"date" : ISODate("2017-04-24T14:04:34.447Z")
}
/* 2 */
{
"user_id" : "bcd021",
"status" : "D",
"date" : ISODate("2017-04-24T14:04:34.447Z")
}
What i want is to format the datetime in the output something like,
/* 1 */
{
"user_id" : "bcd020",
"status" : "D",
"date" : 2017-04-24 14:04:34
}
/* 2 */
{
"user_id" : "bcd021",
"status" : "D",
"date" : 2017-04-24 14:04:34
}
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.
MongoDB will store date and time information using UTC internally, but can easily convert to other timezones at time of retrieval as needed.
MongoDB stores times in UTC by default, and will convert any local time representations into this form. Applications that must operate or report on some unmodified local time value may store the time zone alongside the UTC timestamp, and compute the original local time in their application logic.
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.
Solution is using aggregation pipeline as stated by Veeram in comments section
db.getCollection('people').aggregate([
{
$project:{
datetime: {$dateToString: {format: "%G-%m-%d %H:%M:%S",date: "$datetime"}},
age : 1
}
}
]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With