话不多说,直接先上代码:
// 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$adddate$toDate
另外:
$group$project