db.go 1009 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package db
  2. import (
  3. "go.mongodb.org/mongo-driver/mongo"
  4. "infish.cn/comm"
  5. )
  6. type MongoDB struct {
  7. Client *mongo.Client
  8. Database *mongo.Database
  9. Databases map[string]*mongo.Database //所有数据库
  10. }
  11. var MongoClient *MongoDB
  12. func (db *MongoDB) GetCollection(name string) *mongo.Collection {
  13. return db.Database.Collection(name)
  14. }
  15. func (db *MongoDB) GetDbCollection(dbname string, name string) *mongo.Collection {
  16. if len(dbname) < 1 {
  17. return db.GetCollection(name)
  18. }
  19. return db.GetOrCreateDatabase(dbname).Collection(name)
  20. }
  21. func (db *MongoDB) GetOrCreateDatabase(name string) *mongo.Database {
  22. datab := db.Databases[name]
  23. if datab == nil {
  24. datab = db.Client.Database(name)
  25. db.Databases[name] = datab
  26. }
  27. return datab
  28. }
  29. func NewMongoDB(bus *comm.NatsBus) *MongoDB {
  30. inst, err := bus.NewMongoDBFromConfig("box-mongo")
  31. if err != nil {
  32. panic(err)
  33. }
  34. MongoClient = &MongoDB{Client: inst.Client, Database: inst.Database, Databases: map[string]*mongo.Database{}}
  35. return MongoClient
  36. }