How to convert NumberLong to Date in MongoDB's shell?

16,634

Solution 1

NumberLong(123123123123131).toNumber().toString()

Solution 2

For my own future reference (and incorporating the other answers):

db.mycollection.aggregate([
  {$match:{"userId":"d1792d83-d854-44d5-9jc5-e3e20435958b"}},
  {$project:{newDate:Date("$numberLongDate")}}
])

Solution 3

I'm using expressions like that:

>Date(NumberLong("1397051113715")); 

it will be work too.

Share:
16,634

Related videos on Youtube

Ryan
Author by

Ryan

Updated on October 12, 2022

Comments

  • Ryan
    Ryan over 1 year

    I am storing unix timestamp as MongoDB's NumberLong type (millisecond) , how to convert to human readable date string in the Mongo shell?

  • JohnnyHK
    JohnnyHK over 9 years
    1413382500151 is just a Number type, not a NumberLong.
  • fred271828
    fred271828 over 6 years
    On second view, this doesn't seem to work. It's returning the same Date for every $numberLongDate.
  • fred271828
    fred271828 over 6 years
    Here's the fix: newDate:{$add: [new Date("1970-01-01"), "$numberLongDate"]}.
  • davo777
    davo777 over 4 years
    Hi fwc, I've been trying to emulate your code above and when I run it it returns Nulls in all the new date columns. Can you see what I'm doing wrong? db.mycoll.aggregate([ {$project:{newDate: {$add: [new Date("1970-01-01"), "$numberLongDate"]}}}])
  • fred271828
    fred271828 over 4 years
    Tough to tell, $numberLongDate needs to be the name of your date field maybe?