db.go 1.0 KB

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