Mongoid按日期分组

时间:2015-02-16 14:01:47

标签: ruby-on-rails mongodb 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上找到的不同的东西,这个对我很有用: Best way to group by date with 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}},
])

有什么建议吗?

1 个答案:

答案 0 :(得分:2)

在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的总和