I am using mongodb aggregation to aggregate set of data. My situation is a bit complex. I've a collection as following:
{
startTime: ISODate("2014-12-31T10:20:30Z"),
customerId: 123,
ping: "2",
link: "3"
}
Now I want to aggregate data to another collection as following:
{
_id: {
day: ISODate("2014-12-31T00:00:00Z"),
customerId: 123
},
hours: [
{
hour: ISODate("2014-12-31T10:00:00Z"),
pings: 2,
links: 3
},
{
hour: ISODate("2014-12-31T11:00:00Z"),
pings: 5,
links: 6
}
]
}
As you can see the data is group by day first and then by hours. I've got following aggregation query to group them by day but how to group them further by hours? Any Idea?
var pipeline = [
{
$project : {
startTime : 1,
customerId: 1,
ping:1,
link:1,
date : "$startTime",
h : {
"$hour" : "$startTime"
},
m : {
"$minute" : "$startTime"
},
s : {
"$second" : "$startTime"
},
ml : {
"$millisecond" : "$startTime"
}
}
},
{
$project: {
startTime : 1,
customerId: 1,
ping:1,
link:1,
date : {
"$subtract" : [
"$date",
{
"$add" : [
"$ml",
{
"$multiply" : [
"$s",
1000
]
},
{
"$multiply" : [
"$m",
60,
1000
]
},
{
"$multiply" : [
"$h",
60,
60,
1000
]
}
]
}
]
}
}
},
{
$match: {
"startTime": {
$gte: new ISODate("2013-12-01T07:00:00Z"),
$lte: new ISODate("2014-01-01T08:00:00Z"),
}
}
},
// Aggregate the data
{
$group: {
_id: {day : "$date", customerId: "$customerId"},
pings : {$sum: "$ping"},
links : {$sum: "$links"}
}
}
];