mgotool.go 5.9 KB

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