If you have documents that store dates as Date objects, but you want to return them in a different format, you can use the Show
For example, you might want a date to be returned in 0 format instead of the long 1 format that includes minutes, seconds, milliseconds, etcThe ExampleSuppose we have a collection called 3 with the following documents:{ "_id" : 1, "name" : "Scratch", "born" : ISODate("2021-01-03T23:30:15.123Z") } { "_id" : 2, "name" : "Meow", "born" : ISODate("2019-12-08T04:00:20.112Z") } { "_id" : 3, "name" : "Fluffy", "born" : ISODate("2020-09-24T10:45:01.007Z") } We can use For example, let’s remove the seconds and milliseconds from the date:
Result: { "_id" : 1, "name" : "Scratch", "formattedDate" : "2021-01-03 23:30" } { "_id" : 2, "name" : "Meow", "formattedDate" : "2019-12-08 04:00" } { "_id" : 3, "name" : "Fluffy", "formattedDate" : "2020-09-24 10:45" } We were able to format the date by using the 5 parameter. This is an optional parameter that allows you to use zero or more format specifiers to indicate how the date should be formatted.See MongoDB Date in db.cats.aggregate( [ { $project: { name: 1, formattedDate: { $dateToString: { format: "%Y-%m-%d %H:%M", date: "$born" } } } } ] )8 FormatHere’s another example that converts the dates to 8 format:
Result: { "formattedDate" : "03/01/2021" } { "formattedDate" : "08/12/2019" } { "formattedDate" : "24/09/2020" } Date in db.cats.aggregate( [ { $project: { name: 1, formattedDate: { $dateToString: { format: "%Y-%m-%d %H:%M", date: "$born" } } } } ] )0 FormatOr to put it in 0 format, we can simply switch the first two format specifiers around:
Result: { "formattedDate" : "01/03/2021" } { "formattedDate" : "12/08/2019" } { "formattedDate" : "09/24/2020" } Return a Single Date PartYou can include as many or as few format specifiers as you wish. For example, you could use just one format specifier to output just the year part of the date. Example:
Result: { "formattedDate" : "2021" } { "formattedDate" : "2019" } { "formattedDate" : "2020" } Although, bear in mind that there are other ways to extract just a single date part from a Date object. For example, you can use the { "_id" : 1, "name" : "Scratch", "formattedDate" : "2021-01-03 23:30" } { "_id" : 2, "name" : "Meow", "formattedDate" : "2019-12-08 04:00" } { "_id" : 3, "name" : "Fluffy", "formattedDate" : "2020-09-24 10:45" }2 operator to extract the year. Here are the various operators for extracting each specific date part:
You can also use the 6 operator to return a document that contains all the various date parts separated into their own field. |