您的位置 首页 golang

golang 中mongodb利用时间戳进行分组统计

话不多说,直接先上代码:

// StatGameActive 游戏活跃人数func StatGameActive(start, end int64, gameID string) map[string]int {    type resp struct {        Date    string `bson:"date"`        Count   int    `bson:"count"`    }    var (        m    career.GameLoginLog        data []resp        rs   = make(map[string]int)    )    where := bson.M{"created_at": bson.M{"$gte": start, "$lte": end}, "game_id": gameID}    dateBson := bson.M{"$dateToString": bson.M{"format": "%Y-%m-%d", "date": bson.M{"$toDate": bson.M{"$add": bson.A{ 28800000, bson.M{"$multiply": bson.A{"$created_at", 1000}} } } }}}    pipe:= []bson.M{        {"$match": where},        {"$project": bson.M{"date": dateBson, "user_id": 1} },        {"$group": bson.M{"_id":bson.M{"date": "$date", "user": "$user_id"}}},        {"$group": bson.M{"_id": "$_id.date",  "count": bson.M{"$sum": 1}}},        {"$project": bson.M{"date": "$_id","count":1, "_id": 0}},    }    _ = mongo.Collection(m).AggregateWithError(pipe, &data)    for _, v := range data {        rs[v.Date] = v.Count    }    return rs}

关键内容在:bson.M{"$toDate": bson.M{"$add": bson.A{ 28800000, bson.M{"$multiply": bson.A{"$created_at", 1000}} } } ;
$created_at:数据库字段,这儿存的是秒,故将其转为毫秒。
$add:接收一个slice,值为:date 或者 数字,意思为将 数据相加;28800000:东八区毫秒数。
$toDate: 将时间戳转为 mongo的 date类型,需要注意的是:这里的时间戳必须以毫秒进行

另外:

管道是个好东西,需要灵活使用。其主题思想类似 水流,一层一层将数据处理后传递到下一层进行处理;所以在使用的时候不要局限在一定要将同一类型的语句写在同一个当中。类似此处$group$project.


文章来源:智云一二三科技

文章标题:golang 中mongodb利用时间戳进行分组统计

文章地址:https://www.zhihuclub.com/2788.shtml

关于作者: 智云科技

热门文章

网站地图