Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 399
Nathan Reese Avatar asked Mar 10 '14 18:03

Nathan Reese


People also ask

How do I change the Date format in aggregation in MongoDB?

If you have documents that store dates as Date objects, but you want to return them in a different format, you can use the $dateToString aggregate pipeline operator. The $dateToString operator converts the Date object to a string, and optionally allows you to specify a format for the resulting output.

How do I query a Date in MongoDB?

How does Date Query work in MongoDB? We can use date () command to get a date as a string in a query without the new keyword or MongoDB shell. While creating a new date object, we can specify the date object as follows.

How does MongoDB store Date of birth?

Simply use: new Date("<YYYY-mm-dd>"); Which returns the ISODate with the specified date without a timestamp. MongoDB uses the ISO-8601 date notation, to represent date objects.

How is Date stored in MongoDB?

MongoDB will store date and time information using UTC internally, but can easily convert to other timezones at time of retrieval as needed. Because this is mainly implemented to help coordinate internal processes like replication and sharding, you should probably not use this in your own application's logic.


1 Answers

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")] }
    }}
]);
like image 148
joao Avatar answered Oct 23 '22 04:10

joao