mgotool.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. package main
  2. import (
  3. "context"
  4. "log"
  5. "time"
  6. "go.mongodb.org/mongo-driver/bson"
  7. "go.mongodb.org/mongo-driver/mongo"
  8. "go.mongodb.org/mongo-driver/mongo/options"
  9. )
  10. type MgoSess struct {
  11. Db string
  12. Coll string
  13. Query interface{}
  14. Sorts []string
  15. Hints interface{}
  16. fields interface{}
  17. limit int64
  18. skip int64
  19. M *MongodbSim
  20. }
  21. type MgoIter struct {
  22. Cursor *mongo.Cursor
  23. }
  24. func (mt *MgoIter) Next(result interface{}) bool {
  25. if mt.Cursor != nil {
  26. if mt.Cursor.Next(nil) {
  27. err := mt.Cursor.Decode(result)
  28. if err != nil {
  29. log.Println("mgo cur err", err.Error())
  30. mt.Cursor.Close(nil)
  31. return false
  32. }
  33. return true
  34. } else {
  35. mt.Cursor.Close(nil)
  36. return false
  37. }
  38. } else {
  39. return false
  40. }
  41. }
  42. func (ms *MgoSess) DB(name string) *MgoSess {
  43. ms.Db = name
  44. return ms
  45. }
  46. func (ms *MgoSess) C(name string) *MgoSess {
  47. ms.Coll = name
  48. return ms
  49. }
  50. func (ms *MgoSess) Find(q interface{}) *MgoSess {
  51. ms.Query = q
  52. return ms
  53. }
  54. func (ms *MgoSess) Select(fields interface{}) *MgoSess {
  55. ms.fields = fields
  56. return ms
  57. }
  58. func (ms *MgoSess) Limit(limit int64) *MgoSess {
  59. ms.limit = limit
  60. return ms
  61. }
  62. func (ms *MgoSess) Skip(skip int64) *MgoSess {
  63. ms.skip = skip
  64. return ms
  65. }
  66. func (ms *MgoSess) Sort(sorts ...string) *MgoSess {
  67. ms.Sorts = sorts
  68. return ms
  69. }
  70. func (ms *MgoSess) Hint(hint interface{}) *MgoSess {
  71. ms.Hints = hint
  72. return ms
  73. }
  74. func (ms *MgoSess) Iter() *MgoIter {
  75. it := &MgoIter{}
  76. find := options.Find()
  77. if ms.skip > 0 {
  78. find.SetSkip(ms.skip)
  79. }
  80. if ms.limit > 0 {
  81. find.SetLimit(ms.limit)
  82. }
  83. find.SetBatchSize(300)
  84. if len(ms.Sorts) > 0 {
  85. sort := bson.M{}
  86. for _, k := range ms.Sorts {
  87. switch k[:1] {
  88. case "-":
  89. sort[k[1:]] = -1
  90. case "+":
  91. sort[k[1:]] = 1
  92. default:
  93. sort[k] = 1
  94. }
  95. }
  96. find.SetSort(sort)
  97. }
  98. if ms.Hints != nil {
  99. find.SetHint(ms.Hints)
  100. }
  101. if ms.fields != nil {
  102. find.SetProjection(ms.fields)
  103. }
  104. cur, err := ms.M.C.Database(ms.Db).Collection(ms.Coll).Find(ms.M.Ctx, ms.Query, find)
  105. if err != nil {
  106. log.Println("mgo find err", err.Error())
  107. } else {
  108. it.Cursor = cur
  109. }
  110. return it
  111. }
  112. type MongodbSim struct {
  113. MongodbAddr string
  114. Size int
  115. // MinSize int
  116. DbName string
  117. C *mongo.Client
  118. Ctx context.Context
  119. ShortCtx context.Context
  120. pool chan bool
  121. }
  122. func (m *MongodbSim) GetMgoConn() *MgoSess {
  123. //m.Open()
  124. ms := &MgoSess{}
  125. ms.M = m
  126. return ms
  127. }
  128. func (m *MongodbSim) DestoryMongoConn(ms *MgoSess) {
  129. //m.Close()
  130. ms.M = nil
  131. ms = nil
  132. }
  133. func (m *MongodbSim) InitPool() {
  134. opts := options.Client()
  135. opts.SetConnectTimeout(3 * time.Second)
  136. opts.ApplyURI("mongodb://" + m.MongodbAddr)
  137. opts.SetMaxPoolSize(uint64(m.Size))
  138. m.pool = make(chan bool, m.Size)
  139. opts.SetMaxConnIdleTime(2 * time.Hour)
  140. m.Ctx, _ = context.WithTimeout(context.Background(), 99999*time.Hour)
  141. m.ShortCtx, _ = context.WithTimeout(context.Background(), 1*time.Minute)
  142. client, err := mongo.Connect(m.ShortCtx, opts)
  143. if err != nil {
  144. log.Println("mgo init error:", err.Error())
  145. } else {
  146. m.C = client
  147. log.Println("init success")
  148. }
  149. }
  150. func (m *MongodbSim) Open() {
  151. m.pool <- true
  152. }
  153. func (m *MongodbSim) Close() {
  154. <-m.pool
  155. }
  156. //批量插入
  157. func (m *MongodbSim) UpSertBulk(c string, doc ...[]map[string]interface{}) bool {
  158. m.Open()
  159. defer m.Close()
  160. coll := m.C.Database(m.DbName).Collection(c)
  161. var writes []mongo.WriteModel
  162. for _, d := range doc {
  163. write := mongo.NewUpdateOneModel()
  164. write.SetFilter(d[0])
  165. write.SetUpdate(d[1])
  166. write.SetUpsert(true)
  167. writes = append(writes, write)
  168. }
  169. _, e := coll.BulkWrite(m.Ctx, writes)
  170. if e != nil {
  171. log.Println("mgo upsert error:", e.Error())
  172. return false
  173. }
  174. return true
  175. }
  176. //批量插入
  177. func (m *MongodbSim) SaveBulk(c string, doc ...map[string]interface{}) bool {
  178. m.Open()
  179. defer m.Close()
  180. coll := m.C.Database(m.DbName).Collection(c)
  181. var writes []mongo.WriteModel
  182. for _, d := range doc {
  183. write := mongo.NewInsertOneModel()
  184. write.SetDocument(d)
  185. writes = append(writes, write)
  186. }
  187. _, e := coll.BulkWrite(m.Ctx, writes)
  188. if e != nil {
  189. log.Println("mgo savebulk error:", e.Error())
  190. return false
  191. }
  192. return true
  193. }
  194. //保存
  195. func (m *MongodbSim) Save(c string, doc map[string]interface{}) interface{} {
  196. m.Open()
  197. defer m.Close()
  198. coll := m.C.Database(m.DbName).Collection(c)
  199. r, err := coll.InsertOne(m.Ctx, doc)
  200. if err != nil {
  201. return nil
  202. }
  203. return r.InsertedID
  204. }
  205. //更新by Id
  206. func (m *MongodbSim) UpdateById(c, id string, doc map[string]interface{}) bool {
  207. m.Open()
  208. defer m.Close()
  209. coll := m.C.Database(m.DbName).Collection(c)
  210. _, err := coll.UpdateOne(m.Ctx, map[string]interface{}{"_id": StringTOBsonId(id)}, doc)
  211. if err != nil {
  212. return false
  213. }
  214. return true
  215. }
  216. //删除
  217. func (m *MongodbSim) Delete(c, id string) int64 {
  218. m.Open()
  219. defer m.Close()
  220. coll := m.C.Database(m.DbName).Collection(c)
  221. r, err := coll.DeleteOne(m.Ctx, map[string]interface{}{"_id": StringTOBsonId(id)})
  222. if err != nil {
  223. return 0
  224. }
  225. return r.DeletedCount
  226. }