Mongoid按日期分组

这是我的文件:

{ event_type: 'click', created_at: '2015-02-15 10:00:00', user_id: 100 } 

我需要每天使用event_type = click对唯一身份用户求和。 得到类似的东西:

 { count: 320, date: '2015-02-15' } { count: 451, date: '2015-02-16' } 

(注意日期格式)

我尝试了很多我在SO上找到的不同的东西,这个对我来说几乎有用 : 用Mongoid按日期分组的最佳方法我只是想不出如何修改它来完全按照我的需要做。

这是几乎做我想用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}}, ]) 

有什么建议?

在mongo 2.8 $ dateToString提供将ISO日期转换为字符串格式的工具,因此下面的查询可以解决您的问题

  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 } }) 

在上面的查询中,第一组创建日期明智组,user_id和第二组再次根据日期计算user_id的总和