statisticsShutdownRepo.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package mongo
  2. import (
  3. "context"
  4. "fwh-toolbox-server/database"
  5. "fwh-toolbox-server/domain"
  6. "time"
  7. "go.mongodb.org/mongo-driver/bson"
  8. "go.mongodb.org/mongo-driver/mongo"
  9. "go.mongodb.org/mongo-driver/mongo/options"
  10. )
  11. // 从数据库获取Shutdown统计数据
  12. func GetStatisticsShutdown(date string) (*domain.ShutdownStatisticsItem, error) {
  13. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  14. defer cancel()
  15. collection := database.GetCollection("StatisticsShutdown")
  16. filter := bson.M{}
  17. // 条件
  18. if date != "" {
  19. filter["date"] = date
  20. }
  21. findOptions := options.FindOne().
  22. SetProjection(bson.M{
  23. "_id": 1,
  24. "date": 1,
  25. "siteMap": 1,
  26. "alarmMap": 1,
  27. })
  28. var item domain.ShutdownStatisticsItem
  29. err := collection.FindOne(ctx, filter, findOptions).Decode(&item)
  30. if err != nil {
  31. return nil, err
  32. }
  33. return &item, nil
  34. }
  35. // 插入或更新一条Shutdown统计数据到数据库
  36. func InsertStatisticsShutdown(data domain.ShutdownStatisticsItem) error {
  37. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  38. defer cancel()
  39. collection := database.GetCollection("StatisticsShutdown")
  40. // 创建日期字段唯一索引
  41. collection.Indexes().CreateOne(ctx, mongo.IndexModel{
  42. Keys: bson.M{"date": 1},
  43. Options: options.Index().SetUnique(true),
  44. })
  45. filter := bson.M{"date": data.Date}
  46. update := bson.M{"$set": bson.M{"siteMap": data.SiteMap}}
  47. opts := options.Update().SetUpsert(true)
  48. _, err := collection.UpdateOne(ctx, filter, update, opts)
  49. if err != nil {
  50. return err
  51. }
  52. return nil
  53. }