0

I have list of object in mongo mongo version I am using 4.4 ,

I have list of object something like this

{
    "_id" : "123456",
    "datevalue" : NumberLong(1564079400000),
}

now my requirement is to format the datevalue in mm/dd/yyyy format , This is what I am doing

db.repo.find({"value" : true}).forEach(data=>{
    let date = Date(data.datevalue)
    print(date)
     })

And I am recieving response as

Fri Feb 18 2022 17:21:49 GMT+0530 (IST)

But I require format like

 02/18/2022

1 Answers1

0

If I've understood correctly you can use projection to get the output as string with your desired format.

The query do a trick, add new Date(0) to your milliseconds to get as Date object. Then you can parse to string using $dateToString and the format %m/%d/%Y.

Check the docs about $dateToString for more information.

db.repo.find({"value" : true},
{
  "datevalue": {
    "$dateToString": {
      "date": {
        "$add": [
          new Date(0),
          "$datevalue"
        ]
      },
      "format": "%m/%d/%Y"
    }
  }
})

Example here

J.F.
  • 13,927
  • 9
  • 27
  • 65