问题
this is the kind of document I have:
{
event_type: 'click',
created_at: '2015-02-15 10:00:00',
user_id: 100
}
I need to sum unique users per day with event_type = click. To get something like:
{
count: 320,
date: '2015-02-15'
}
{
count: 451,
date: '2015-02-16'
}
(note the date format)
I've tried many different things I found on SO, this one almost worked for me: Best way to group by date with Mongoid I just couldn't figure out how to modify it to do exactly what I need.
This is the raw query that's almost doing what I want to achieve with Mongoid:
db.events.aggregate([
{$match: {event_type: 'click', created_at: {
$gte: ISODate('2015-01-01T00:00:00.000Z'),
$lt: ISODate('2016-01-01T00:00:00.000Z')
}}},
{$group: {
_id: {user_id: '$user_id', account_id: '$account_id', created_at: {
day: { $dayOfMonth: '$created_at' },
month: { $month: '$created_at' },
year: { $year: '$created_at'}
}},
'count': {'$sum': 1}
}
},
{$sort: {created_at: -1}},
])
Any suggestions?
回答1:
in mongo 2.8 $dateToString provide facility to convert ISO date to string format so below query may solve your problem
db.collectionName.aggregate({
"$match": {
"event_type": "click"
}
}, {
"$project": {
"yearMonthDay": {
"$dateToString": {
"format": "%Y-%m-%d",
"date": "$created_at"
}
},
"user_id": "$user_id"
}
}, {
"$group": {
"_id": {
"user_id": "$user_id",
"date": "$yearMonthDay"
}
}
}, {
"$group": {
"_id": "$_id.date",
"count": {
"$sum": "$_id.user_id"
}
}
}, {
"$project": {
"date": "$_id",
"count": "$count",
"_id": 0
}
})
In above query first group create group of date wise and user_id and second group again count sum of user_id according to date
来源:https://stackoverflow.com/questions/28543150/mongoid-grouping-by-date