forked from all_user/stat_center
106 lines
2.4 KiB
Go
106 lines
2.4 KiB
Go
package minutestatmod
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"stat/common/log"
|
|
"stat/common/mongos"
|
|
"time"
|
|
|
|
"go.mongodb.org/mongo-driver/mongo"
|
|
"go.mongodb.org/mongo-driver/mongo/options"
|
|
|
|
"go.mongodb.org/mongo-driver/bson"
|
|
)
|
|
|
|
// 初始化model
|
|
func Init() {
|
|
// 获取数据库表
|
|
db = mongos.New(mongos.MgoManager, CollMinuteStat)
|
|
|
|
indexes := []mongo.IndexModel{
|
|
{
|
|
Keys: bson.D{{Key: "sumDate", Value: 1}, {Key: "updatedAt", Value: 1}},
|
|
}, {
|
|
Keys: bson.D{{Key: "sumDate", Value: 1}, {Key: "appId", Value: 1}},
|
|
},
|
|
}
|
|
|
|
if _, err := db.CreateIndex(context.Background(), indexes); err != nil {
|
|
panic(fmt.Sprintf("Model %s InitIndex error %+v", CollMinuteStat, err))
|
|
}
|
|
}
|
|
|
|
func UpsertMinuteStatEx(ctx context.Context,
|
|
filter bson.M, update bson.M) error {
|
|
if _, err := db.UpsertOneEx(ctx, filter, update); err != nil {
|
|
log.Info("minutestatmod:UpsertMinuteStatEx db.InsertOne failed",
|
|
log.E(err), log.Any("filter", filter))
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func UpsertMinuteDocStat(ctx context.Context, sumDate time.Time, appId int32, update *MinuteStatDoc) error {
|
|
now := time.Now()
|
|
update.UpdatedAt = &now
|
|
|
|
filter := bson.M{
|
|
"appId": appId,
|
|
"sumDate": sumDate,
|
|
}
|
|
|
|
upsertDoc := bson.M{
|
|
"$set": update,
|
|
"$setOnInsert": filter,
|
|
}
|
|
|
|
if _, err := db.UpsertOneEx(ctx, filter, upsertDoc); err != nil {
|
|
log.Info("minutestatmod:UpsertMinuteStatEx db.InsertOne failed",
|
|
log.E(err), log.Any("filter", filter))
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// UpsertDailyStat 更新或插入一条统计记录
|
|
func UpsertMinuteStat(ctx context.Context, sumDate time.Time, appId int32, doc MinuteStatDoc) (err error) {
|
|
var filter = bson.M{
|
|
"sumDate": sumDate,
|
|
"appId": appId,
|
|
}
|
|
var update = mongos.ToBsonM(doc)
|
|
|
|
exists, err := db.Exists(ctx, filter)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if exists {
|
|
_, err = db.UpdateOne(ctx, filter, bson.M{"$set": update})
|
|
} else {
|
|
insertDoc := update
|
|
insertDoc["sumDate"] = sumDate
|
|
insertDoc["appId"] = appId
|
|
|
|
_, err = db.InsertOne(ctx, insertDoc)
|
|
}
|
|
|
|
return
|
|
}
|
|
|
|
func GetMinuteStatList(ctx context.Context, start, end time.Time, appId int32) (data []MinuteStatMod, err error) {
|
|
filter := bson.M{"sumDate": bson.M{"$gte": start, "$lt": end}, "appId": appId}
|
|
|
|
sort := bson.D{{Key: "sumDate", Value: 1}}
|
|
|
|
opts := options.Find().SetSort(sort)
|
|
|
|
if err = db.Find(ctx, &data, filter, opts); err != nil {
|
|
log.Error("minuteStat GetMinuteStatList Find err", log.E(err))
|
|
return
|
|
}
|
|
|
|
return
|
|
}
|