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

2 Answers 2

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")] }
    }}
]);
5
  • 1
    Thanks for the quick turn around. Seems like an odd way of getting the value but it works Commented Mar 10, 2014 at 21:12
  • @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_time
    – Neil Lunn
    Commented Mar 10, 2014 at 22:20
  • Make sure to parse date as UTC 'new Date(Date.UTC('1-1-1970'))' Commented Mar 11, 2014 at 14:47
  • 4
    new Date(0) should also give you the 'beginning of time' epoch Commented Feb 27, 2017 at 6:52
  • @AchintyaAshok and new Date(0) also ensures that local/server time zone doesn't cause any issues
    – Kip
    Commented Jun 1, 2021 at 19:58
0

Here's how you can add an aggregation pipeline.

here's how you can add in aggregationPipleine

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.