mgotool.go 5.4 KB

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