Counting user activity with MongoDB Aggregate Framework -


i try keep simple. have user objects, inside user objects have field array contains isodates of the days user has logged in. count how many users logged in on particular date dates exist.

sample user:

{   "_id": "some_id",   "name": "bob",   "logins": [isodate, isodate, isodate...],    //...  } 

i'd output tells me like:

{   "date": isodate,   "number_of_users_logged_in": 10 } 

is possible? how go doing it?

you need use $unwind operation explode array, $group date (using granularity want) , $project date , count, below:

db.user.aggregate({     $unwind: "$logins" }, {     $group: {         _id: {             year: {                 $year: "$logins"             },             month: {                 $month: "$logins"             },             day: {                 $dayofmonth: "$logins"             },             hour: {                 $hour: "$logins"             }         },         date: {             $first: "$logins"         },         count: {             $sum: 1         }     } }, {     $project: {         _id : 0,         date: "$date",         number_of_users_logged_in: "$count"     } }) 

i grouped year/month/day/hour.


Comments