Reputation: 124
i have to collect data for a graphic that shows visits, and for example if i want to show a day in the graph i have to divide the visits per hour. my object is like this
{
"_id" : ObjectId("5ab1119b646e371568c8cf9e"),
"date" : ISODate("2018-03-20T13:46:30.018Z"),
"__v" : 0
}
i tried this code
db.getCollection('monitors').aggregate([{
"$group": {
"_id": {
"year": {"$year": "$date"},
"dayOfYear": {"$dayOfYear": "$date"},
"interval": {"$subtract": [{"$minute": "$date"}, {"$mod": [{"$minute": "$date"}, 60]}]}
}, "count": {"$sum": 1}
}
}]))
and it works but it collects only datas per day. i need to collect also per hour. thanks a lot.
Upvotes: 5
Views: 1261
Reputation: 75984
Not sure why you didn't use $hour
in the $group
stage. You will need two groups one for day and another one for hour.
Something like
db.monitors.aggregate([
{"$group":{
"_id":{
"year":{"$year":"$date"},
"dayOfYear":{"$dayOfYear":"$date"},
"hour":{"$hour":"$date"}
},
"count":{"$sum":1}
}},
{"$group":{
"_id":{
"year":"$_id.year",
"dayOfYear":"$_id.dayOfYear"
},
"dailyCount":{"$sum":"$count"},
"hourlyData":{"$push":{"hour":"$_id.hour","count":"$count"}}
}}
])
Upvotes: 4