Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert date to timestamp mongodb

I have a problem with the date in MongoDB. When I create a post I get the date with Date.now(). When I check the DB it is stored as this: ISODate("2018-12-08T09:40:38.623+0000").

If I do a normal GraphQL query I get as result: "created_at": "1544262038623". In my schema the query is defined as created_at: String. Question number 1: How can I make the query to show me the date and not the timestamp since epoch?

Question number 2: I want to get the timestamp to do some aggregate calculation. But there it's always in the date format and I can't get the timestamp, no matter what I do. I tried: $toDecimal, new Date("$created_at") and other things. How do I do that? I need the milliseconds since epoch like in the query above (1544262038623).

Addiotional info: Working with mongoose and apollo. MongoDB is mLab.

Post.aggregate([
  { $match: { author_id: "uRKNnDZIv" }},
  { $addFields: { 
    timestamp: "$created_at"
  }
])

1 Answers

If you want to convert date to timestamp then you can use $toLong aggregation

Post.aggregate([
  { "$match": { "author_id": "uRKNnDZIv" }},
  { "$addFields": { 
    "timestamp": { "$toLong": "$created_at" }
  }}
])

And If you want to convert timestamp to date then you can use $toDate aggregation

Post.aggregate([
  { "$match": { "author_id": "uRKNnDZIv" }},
  { "$addFields": { 
    "timestamp": { "$toDate": "$created_at" }
  }}
])
like image 193
Ashh Avatar answered Mar 06 '26 18:03

Ashh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!