| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667 |
- package mongo
- import (
- "context"
- "fwh-toolbox-server/database"
- "fwh-toolbox-server/domain"
- "time"
- "go.mongodb.org/mongo-driver/bson"
- "go.mongodb.org/mongo-driver/mongo"
- "go.mongodb.org/mongo-driver/mongo/options"
- )
- // 从数据库获取Shutdown统计数据
- func GetStatisticsShutdown(date string) (*domain.ShutdownStatisticsItem, error) {
- ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
- defer cancel()
- collection := database.GetCollection("StatisticsShutdown")
- filter := bson.M{}
- // 条件
- if date != "" {
- filter["date"] = date
- }
- findOptions := options.FindOne().
- SetProjection(bson.M{
- "_id": 1,
- "date": 1,
- "siteMap": 1,
- "alarmMap": 1,
- })
- var item domain.ShutdownStatisticsItem
- err := collection.FindOne(ctx, filter, findOptions).Decode(&item)
- if err != nil {
- return nil, err
- }
- return &item, nil
- }
- // 插入或更新一条Shutdown统计数据到数据库
- func InsertStatisticsShutdown(data domain.ShutdownStatisticsItem) error {
- ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
- defer cancel()
- collection := database.GetCollection("StatisticsShutdown")
- // 创建日期字段唯一索引
- collection.Indexes().CreateOne(ctx, mongo.IndexModel{
- Keys: bson.M{"date": 1},
- Options: options.Index().SetUnique(true),
- })
- filter := bson.M{"date": data.Date}
- update := bson.M{"$set": bson.M{"siteMap": data.SiteMap}}
- opts := options.Update().SetUpsert(true)
- _, err := collection.UpdateOne(ctx, filter, update, opts)
- if err != nil {
- return err
- }
- return nil
- }
|