mgotool.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. package main
  2. import (
  3. "context"
  4. "log"
  5. "strings"
  6. "time"
  7. "go.mongodb.org/mongo-driver/bson"
  8. "go.mongodb.org/mongo-driver/bson/primitive"
  9. "go.mongodb.org/mongo-driver/mongo"
  10. "go.mongodb.org/mongo-driver/mongo/options"
  11. )
  12. type MgoSess struct {
  13. Db string
  14. Coll string
  15. Query interface{}
  16. Sorts []string
  17. fields interface{}
  18. limit int64
  19. skip int64
  20. M *MongodbSim
  21. }
  22. type MgoIter struct {
  23. Cursor *mongo.Cursor
  24. }
  25. func NewMgo(addr, db string, size int) *MongodbSim {
  26. mgo := &MongodbSim{
  27. MongodbAddr: addr,
  28. Size: size,
  29. DbName: db,
  30. }
  31. mgo.InitPool()
  32. return mgo
  33. }
  34. func (mt *MgoIter) Next(result interface{}) bool {
  35. if mt.Cursor != nil {
  36. if mt.Cursor.Next(nil) {
  37. err := mt.Cursor.Decode(result)
  38. if err != nil {
  39. log.Println("mgo cur err", err.Error())
  40. mt.Cursor.Close(nil)
  41. return false
  42. }
  43. return true
  44. } else {
  45. mt.Cursor.Close(nil)
  46. return false
  47. }
  48. } else {
  49. return false
  50. }
  51. }
  52. func (ms *MgoSess) DB(name string) *MgoSess {
  53. ms.Db = name
  54. return ms
  55. }
  56. func (ms *MgoSess) C(name string) *MgoSess {
  57. ms.Coll = name
  58. return ms
  59. }
  60. func (ms *MgoSess) Find(q interface{}) *MgoSess {
  61. ms.Query = q
  62. return ms
  63. }
  64. func (ms *MgoSess) Select(fields interface{}) *MgoSess {
  65. ms.fields = fields
  66. return ms
  67. }
  68. func (ms *MgoSess) Limit(limit int64) *MgoSess {
  69. ms.limit = limit
  70. return ms
  71. }
  72. func (ms *MgoSess) Skip(skip int64) *MgoSess {
  73. ms.skip = skip
  74. return ms
  75. }
  76. func (ms *MgoSess) Sort(sorts ...string) *MgoSess {
  77. ms.Sorts = sorts
  78. return ms
  79. }
  80. func (ms *MgoSess) Iter() *MgoIter {
  81. it := &MgoIter{}
  82. find := options.Find()
  83. if ms.skip > 0 {
  84. find.SetSkip(ms.skip)
  85. }
  86. if ms.limit > 0 {
  87. find.SetLimit(ms.limit)
  88. }
  89. find.SetBatchSize(100)
  90. if len(ms.Sorts) > 0 {
  91. sort := bson.M{}
  92. for _, k := range ms.Sorts {
  93. switch k[:1] {
  94. case "-":
  95. sort[k[1:]] = -1
  96. case "+":
  97. sort[k[1:]] = 1
  98. default:
  99. sort[k] = 1
  100. }
  101. }
  102. find.SetSort(sort)
  103. }
  104. if ms.fields != nil {
  105. find.SetProjection(ms.fields)
  106. }
  107. cur, err := ms.M.C.Database(ms.Db).Collection(ms.Coll).Find(ms.M.Ctx, ms.Query, find)
  108. if err != nil {
  109. log.Println("mgo find err", err.Error())
  110. } else {
  111. it.Cursor = cur
  112. }
  113. return it
  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) Destroy() {
  137. //m.Close()
  138. m.C.Disconnect(nil)
  139. m.C = nil
  140. }
  141. func (m *MongodbSim) InitPool() {
  142. opts := options.Client()
  143. opts.SetConnectTimeout(3 * time.Second)
  144. opts.ApplyURI("mongodb://" + m.MongodbAddr)
  145. opts.SetMaxPoolSize(uint64(m.Size))
  146. m.pool = make(chan bool, m.Size)
  147. opts.SetMaxConnIdleTime(2 * time.Hour)
  148. m.Ctx, _ = context.WithTimeout(context.Background(), 99999*time.Hour)
  149. m.ShortCtx, _ = context.WithTimeout(context.Background(), 1*time.Minute)
  150. client, err := mongo.Connect(m.ShortCtx, opts)
  151. if err != nil {
  152. log.Println("mgo init error:", err.Error())
  153. } else {
  154. m.C = client
  155. }
  156. }
  157. func (m *MongodbSim) Open() {
  158. m.pool <- true
  159. }
  160. func (m *MongodbSim) Close() {
  161. <-m.pool
  162. }
  163. //批量插入
  164. func (m *MongodbSim) UpSertBulk(c string, doc ...[]map[string]interface{}) bool {
  165. m.Open()
  166. defer m.Close()
  167. coll := m.C.Database(m.DbName).Collection(c)
  168. var writes []mongo.WriteModel
  169. for _, d := range doc {
  170. write := mongo.NewUpdateOneModel()
  171. write.SetFilter(d[0])
  172. write.SetUpdate(d[1])
  173. write.SetUpsert(true)
  174. writes = append(writes, write)
  175. }
  176. br, e := coll.BulkWrite(m.Ctx, writes)
  177. if e != nil {
  178. log.Println("mgo upsert error:", e.Error())
  179. return br == nil || br.UpsertedCount == 0
  180. }
  181. // else {
  182. // if r.UpsertedCount != int64(len(doc)) {
  183. // log.Println("mgo upsert uncomplete:uc/dc", r.UpsertedCount, len(doc))
  184. // }
  185. // return true
  186. // }
  187. return true
  188. }
  189. //批量插入
  190. func (m *MongodbSim) SaveBulk(c string, doc ...map[string]interface{}) bool {
  191. m.Open()
  192. defer m.Close()
  193. coll := m.C.Database(m.DbName).Collection(c)
  194. var writes []mongo.WriteModel
  195. for _, d := range doc {
  196. write := mongo.NewInsertOneModel()
  197. write.SetDocument(d)
  198. writes = append(writes, write)
  199. }
  200. br, e := coll.BulkWrite(m.Ctx, writes)
  201. if e != nil {
  202. b := strings.Index(e.Error(), "duplicate") > -1
  203. log.Println("mgo savebulk error:", e.Error())
  204. if br != nil {
  205. log.Println("mgo savebulk size:", br.InsertedCount)
  206. }
  207. return b
  208. }
  209. return true
  210. }
  211. func StringTOBsonId(id string) primitive.ObjectID {
  212. objectId, _ := primitive.ObjectIDFromHex(id)
  213. return objectId
  214. }
  215. //按条件统计
  216. func (m *MongodbSim) Count(c string, q interface{}) int64 {
  217. m.Open()
  218. defer m.Close()
  219. ct := options.Count()
  220. ct.SetMaxTime(180 * time.Second)
  221. res, err := m.C.Database(m.DbName).Collection(c).CountDocuments(m.Ctx, q, ct)
  222. if err != nil {
  223. log.Println("统计错误", err.Error())
  224. }
  225. return res
  226. }
  227. //按条件删除
  228. func (m *MongodbSim) Delete(c string, q interface{}) int64 {
  229. m.Open()
  230. defer m.Close()
  231. ct := options.Delete()
  232. res, err := m.C.Database(m.DbName).Collection(c).DeleteMany(m.Ctx, q, ct)
  233. if err != nil && res == nil {
  234. log.Println("删除错误", err.Error())
  235. }
  236. return res.DeletedCount
  237. }
  238. //按条件更新
  239. func (m *MongodbSim) Update(c string, q, u interface{}) int64 {
  240. m.Open()
  241. defer m.Close()
  242. ct := options.Update()
  243. res, err := m.C.Database(m.DbName).Collection(c).UpdateMany(m.Ctx, q, u, ct)
  244. if err != nil && res == nil {
  245. log.Println("删除错误", err.Error())
  246. }
  247. return res.ModifiedCount
  248. }
  249. //查找一条数据
  250. func (m *MongodbSim) FindOne(c string, q, fields interface{}, sorts []string) (res map[string]interface{}) {
  251. m.Open()
  252. defer m.Close()
  253. of := options.FindOne()
  254. if fields != nil {
  255. of.SetProjection(fields)
  256. }
  257. if len(sorts) > 0 {
  258. sort := bson.M{}
  259. for _, k := range sorts {
  260. switch k[:1] {
  261. case "-":
  262. sort[k[1:]] = -1
  263. case "+":
  264. sort[k[1:]] = 1
  265. default:
  266. sort[k] = 1
  267. }
  268. }
  269. of.SetSort(sort)
  270. }
  271. sr := m.C.Database(m.DbName).Collection(c).FindOne(m.Ctx, q, of)
  272. sr.Decode(&res)
  273. return
  274. }