Home > database >  Change date format on fetch MongoDB
Change date format on fetch MongoDB

Time:10-18

When fetching the default timestamps the format is 2021-10-07T11:16:44.988Z. I want it to be like dd/mm/YYYY. I want to achieve it without using a loop.

CodePudding user response:

Consider a sales collection with the following document:

{
  "_id" : 1,
  "item" : "abc",
  "price" : 10,
  "quantity" : 2,
  "date" : ISODate("2014-01-01T08:15:39.736Z")
}

The following aggregation uses $dateToString to return the date field as formatted strings:

db.sales.aggregate(
   [
     {
       $project: {
          yearMonthDayUTC: { $dateToString: { format: "%Y-%m-%d", date: "$date" } },
           
       }
     }
   ]
)

The operation returns the following result:

{
   "_id" : 1,
   "yearMonthDayUTC" : "2014-01-01"
}

Documentation

  • Related