mgotool.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  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. func (ms *MgoSess) Count() (int64, error) {
  113. return ms.M.C.Database(ms.Db).Collection(ms.Coll).CountDocuments(ms.M.Ctx, ms.Query)
  114. }
  115. type MongodbSim struct {
  116. MongodbAddr string
  117. Size int
  118. // MinSize int
  119. DbName string
  120. C *mongo.Client
  121. Ctx context.Context
  122. ShortCtx context.Context
  123. pool chan bool
  124. }
  125. func (m *MongodbSim) GetMgoConn() *MgoSess {
  126. //m.Open()
  127. ms := &MgoSess{}
  128. ms.M = m
  129. return ms
  130. }
  131. func (m *MongodbSim) DestoryMongoConn(ms *MgoSess) {
  132. //m.Close()
  133. ms.M = nil
  134. ms = nil
  135. }
  136. func (m *MongodbSim) InitPool() {
  137. opts := options.Client()
  138. opts.SetConnectTimeout(3 * time.Second)
  139. opts.ApplyURI("mongodb://" + m.MongodbAddr)
  140. opts.SetMaxPoolSize(uint64(m.Size))
  141. m.pool = make(chan bool, m.Size)
  142. opts.SetMaxConnIdleTime(2 * time.Hour)
  143. m.Ctx, _ = context.WithTimeout(context.Background(), 99999*time.Hour)
  144. m.ShortCtx, _ = context.WithTimeout(context.Background(), 1*time.Minute)
  145. client, err := mongo.Connect(m.ShortCtx, opts)
  146. if err != nil {
  147. log.Println("mgo init error:", err.Error())
  148. } else {
  149. m.C = client
  150. log.Println("init success")
  151. }
  152. }
  153. func (m *MongodbSim) Open() {
  154. m.pool <- true
  155. }
  156. func (m *MongodbSim) Close() {
  157. <-m.pool
  158. }
  159. //批量插入
  160. func (m *MongodbSim) UpSertBulk(c string, doc ...[]map[string]interface{}) bool {
  161. m.Open()
  162. defer m.Close()
  163. coll := m.C.Database(m.DbName).Collection(c)
  164. var writes []mongo.WriteModel
  165. for _, d := range doc {
  166. write := mongo.NewUpdateOneModel()
  167. write.SetFilter(d[0])
  168. write.SetUpdate(d[1])
  169. write.SetUpsert(true)
  170. writes = append(writes, write)
  171. }
  172. _, e := coll.BulkWrite(m.Ctx, writes)
  173. if e != nil {
  174. log.Println("mgo upsert error:", e.Error())
  175. return false
  176. }
  177. return true
  178. }
  179. //批量插入
  180. func (m *MongodbSim) SaveBulk(c string, doc ...map[string]interface{}) bool {
  181. m.Open()
  182. defer m.Close()
  183. coll := m.C.Database(m.DbName).Collection(c)
  184. var writes []mongo.WriteModel
  185. for _, d := range doc {
  186. write := mongo.NewInsertOneModel()
  187. write.SetDocument(d)
  188. writes = append(writes, write)
  189. }
  190. _, e := coll.BulkWrite(m.Ctx, writes)
  191. if e != nil {
  192. log.Println("mgo savebulk error:", e.Error())
  193. return false
  194. }
  195. return true
  196. }
  197. //保存
  198. func (m *MongodbSim) Save(c string, doc map[string]interface{}) interface{} {
  199. m.Open()
  200. defer m.Close()
  201. coll := m.C.Database(m.DbName).Collection(c)
  202. r, err := coll.InsertOne(m.Ctx, doc)
  203. if err != nil {
  204. return nil
  205. }
  206. return r.InsertedID
  207. }
  208. //更新by Id
  209. func (m *MongodbSim) UpdateById(c, id string, doc map[string]interface{}) bool {
  210. m.Open()
  211. defer m.Close()
  212. coll := m.C.Database(m.DbName).Collection(c)
  213. _, err := coll.UpdateOne(m.Ctx, map[string]interface{}{"_id": StringTOBsonId(id)}, doc)
  214. if err != nil {
  215. return false
  216. }
  217. return true
  218. }
  219. //删除
  220. func (m *MongodbSim) Delete(c, id string) int64 {
  221. m.Open()
  222. defer m.Close()
  223. coll := m.C.Database(m.DbName).Collection(c)
  224. r, err := coll.DeleteOne(m.Ctx, map[string]interface{}{"_id": StringTOBsonId(id)})
  225. if err != nil {
  226. return 0
  227. }
  228. return r.DeletedCount
  229. }
  230. func (m *MongodbSim) FindById(c, id string) map[string]interface{} {
  231. m.Open()
  232. defer m.Close()
  233. coll := m.C.Database(m.DbName).Collection(c)
  234. r := coll.FindOne(m.Ctx, map[string]interface{}{"_id": StringTOBsonId(id)})
  235. result := map[string]interface{}{}
  236. _ = r.Decode(&result)
  237. return result
  238. }