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
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 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.
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.
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.
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")] }
}}
]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With