I have a MongoDB collection where records are stored with timestamp in milliseconds. I need to aggregate these records by hour and convert the timestamp to ISODate so that I can use MongoDB's built-in date operators ($hour, $month, etc.)
Here is an example of how records are stored:
{
"data" : { "UserId" : "abc", "ProjId" : "xyz"},
"time" : NumberLong("1395140780706"),
"_id" : ObjectId("532828ac338ed9c33aa8eca7")
}
I am attempting to run the following aggregate query:
db.events.aggregate(
{
$match : {
"time" : { $gte : 1395186209804, $lte : 1395192902825 }
}
},
{
$project : {
_id : "$_id",
dt : {$concat : (Date("$time")).toString()} // need to project as ISODate
}
},
// further processing in $project or $group clause
)
The results produced look like this:
{
"result" : [
{
"_id" : ObjectId("5328da21fd207d9c3567d3ec"),
"dt" : "Fri Mar 21 2014 17:35:46 GMT-0400 (EDT)"
},
{
"_id" : ObjectId("5328da21fd207d9c3567d3ed"),
"dt" : "Fri Mar 21 2014 17:35:46 GMT-0400 (EDT)"
},
...
}
My issue now is that I want to extract hour, day, month, and year from the date, but since it is projected as a string, I cannot use MongoDB's built-in date operators. How do I convert the timestamp from milliseconds to ISO date for operations like the following:
db.events.aggregate(
{
$match : {
"time" : { $gte : 1395186209804, $lte : 1395192902825 }
}
},
{
$project : {
_id : "$_id",
dt : <ISO date from "$time">
}
},
{
$project : {
_id : "$_id",
date : {
hour : {$hour : "$dt"}
}
}
}
)