Is there a way to access a Date as milliseconds since epoch (Date.getTime()) in mongodb aggregation pipeline
Asked Answered
D

2

9

Mongodb provides lots of 'Date Aggregation Operators' such as $dayOfYear, $dayOf Month, and $millisecond. The $millisecond function just returns the milliseconds of the time stamp with a range of 0-999.

Is there a way to access a Date object as milliseconds since epoch in aggregation pipeline?

Thanks,

Nathan

Directoire answered 10/3, 2014 at 18:30 Comment(0)
M
16

You can $subtract the epoch date and the result will be your date milliseconds since epoch:

db.collection.aggregate([
    {$project : {
        "dateInMillis" : {$subtract : ["$date", new Date("1-1-1970")] }
    }}
]);
Mccusker answered 10/3, 2014 at 19:6 Comment(5)
Thanks for the quick turn around. Seems like an odd way of getting the value but it worksDirectoire
@NathanReese It's not odd at all once you realize that the underlying BSON date is actually an epoch timestamp. Which is all this does. The difference between now and the beginning in milliseconds. en.wikipedia.org/wiki/Unix_timeMeir
Make sure to parse date as UTC 'new Date(Date.UTC('1-1-1970'))'Directoire
new Date(0) should also give you the 'beginning of time' epochIndulge
@AchintyaAshok and new Date(0) also ensures that local/server time zone doesn't cause any issuesHeartstrings
O
0

Here's how you can add an aggregation pipeline.

here's how you can add in aggregationPipleine

Oakland answered 7/10, 2023 at 9:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.