mgo.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. package util
  2. import (
  3. "context"
  4. "go.mongodb.org/mongo-driver/bson/primitive"
  5. "go.mongodb.org/mongo-driver/mongo"
  6. "go.mongodb.org/mongo-driver/mongo/options"
  7. "gopkg.in/mgo.v2/bson"
  8. "log"
  9. "time"
  10. )
  11. type Mgo struct {
  12. Uri string
  13. PoolSize uint64
  14. mgoEn *mongo.Client
  15. }
  16. type MgoSess struct {
  17. Db string
  18. Coll string
  19. Query interface{}
  20. Sorts []string
  21. fields interface{}
  22. limit int64
  23. skip int64
  24. M *MongodbSim
  25. }
  26. type MgoIter struct {
  27. Cursor *mongo.Cursor
  28. }
  29. func (mt *MgoIter) Next(result interface{}) bool {
  30. if mt.Cursor != nil {
  31. if mt.Cursor.Next(nil) {
  32. err := mt.Cursor.Decode(result)
  33. if err != nil {
  34. log.Println("mgo cur err", err.Error())
  35. mt.Cursor.Close(nil)
  36. return false
  37. }
  38. return true
  39. } else {
  40. mt.Cursor.Close(nil)
  41. return false
  42. }
  43. } else {
  44. return false
  45. }
  46. }
  47. func (ms *MgoSess) DB(name string) *MgoSess {
  48. ms.Db = name
  49. return ms
  50. }
  51. func (ms *MgoSess) C(name string) *MgoSess {
  52. ms.Coll = name
  53. return ms
  54. }
  55. func (ms *MgoSess) Find(q interface{}) *MgoSess {
  56. ms.Query = q
  57. return ms
  58. }
  59. func (ms *MgoSess) Select(fields interface{}) *MgoSess {
  60. ms.fields = fields
  61. return ms
  62. }
  63. func (ms *MgoSess) Limit(limit int64) *MgoSess {
  64. ms.limit = limit
  65. return ms
  66. }
  67. func (ms *MgoSess) Skip(skip int64) *MgoSess {
  68. ms.skip = skip
  69. return ms
  70. }
  71. func (ms *MgoSess) Sort(sorts ...string) *MgoSess {
  72. ms.Sorts = sorts
  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(100)
  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.fields != nil {
  100. find.SetProjection(ms.fields)
  101. }
  102. cur, err := ms.M.C.Database(ms.Db).Collection(ms.Coll).Find(ms.M.Ctx, ms.Query, find)
  103. if err != nil {
  104. log.Println("mgo find err", err.Error())
  105. } else {
  106. it.Cursor = cur
  107. }
  108. return it
  109. }
  110. type MongodbSim struct {
  111. MongodbAddr string
  112. Size int
  113. // MinSize int
  114. DbName string
  115. C *mongo.Client
  116. Ctx context.Context
  117. ShortCtx context.Context
  118. pool chan bool
  119. UserName string
  120. PassWord string
  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. if m.UserName !="" && m.PassWord !="" {
  140. cre := options.Credential{
  141. Username:m.UserName,
  142. Password:m.PassWord,
  143. }
  144. opts.SetAuth(cre)
  145. }
  146. opts.SetMaxConnIdleTime(2 * time.Hour)
  147. m.Ctx, _ = context.WithTimeout(context.Background(), 99999*time.Hour)
  148. m.ShortCtx, _ = context.WithTimeout(context.Background(), 1*time.Minute)
  149. client, err := mongo.Connect(m.ShortCtx, opts)
  150. if err != nil {
  151. log.Println("mgo init error:", err.Error())
  152. } else {
  153. m.C = client
  154. log.Println("init success")
  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{}) (map[int64]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. r, e := coll.BulkWrite(m.Ctx, writes)
  177. if e != nil {
  178. log.Println("mgo upsert error:", e.Error())
  179. return nil, false
  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 r.UpsertedIDs, 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. _, e := coll.BulkWrite(m.Ctx, writes)
  201. if e != nil {
  202. log.Println("mgo savebulk error:", e.Error())
  203. return false
  204. }
  205. return true
  206. }
  207. //保存
  208. func (m *MongodbSim) Save(c string, doc map[string]interface{}) interface{} {
  209. m.Open()
  210. defer m.Close()
  211. coll := m.C.Database(m.DbName).Collection(c)
  212. r, err := coll.InsertOne(m.Ctx, doc)
  213. if err != nil {
  214. return nil
  215. }
  216. return r.InsertedID
  217. }
  218. //更新by Id
  219. func (m *MongodbSim) UpdateById(c, id string, doc map[string]interface{}) bool {
  220. m.Open()
  221. defer m.Close()
  222. coll := m.C.Database(m.DbName).Collection(c)
  223. _, err := coll.UpdateOne(m.Ctx, map[string]interface{}{"_id": StringTOBsonId(id)}, doc)
  224. if err != nil {
  225. return false
  226. }
  227. return true
  228. }
  229. //删除by id
  230. func (m *MongodbSim) DeleteById(c, id string) int64 {
  231. m.Open()
  232. defer m.Close()
  233. coll := m.C.Database(m.DbName).Collection(c)
  234. r, err := coll.DeleteOne(m.Ctx, map[string]interface{}{"_id": StringTOBsonId(id)})
  235. if err != nil {
  236. return 0
  237. }
  238. return r.DeletedCount
  239. }
  240. //通过条件删除
  241. func (m *MongodbSim) Delete(c string, query map[string]interface{}) int64 {
  242. m.Open()
  243. defer m.Close()
  244. coll := m.C.Database(m.DbName).Collection(c)
  245. r, err := coll.DeleteMany(m.Ctx, query)
  246. if err != nil {
  247. return 0
  248. }
  249. return r.DeletedCount
  250. }
  251. //findbyid
  252. func (m *MongodbSim) FindById(c, id string) map[string]interface{} {
  253. m.Open()
  254. defer m.Close()
  255. coll := m.C.Database(m.DbName).Collection(c)
  256. r := coll.FindOne(m.Ctx, map[string]interface{}{"_id": StringTOBsonId(id)})
  257. v := map[string]interface{}{}
  258. r.Decode(&v)
  259. return v
  260. }
  261. //findone
  262. func (m *MongodbSim) FindOne(c string, query map[string]interface{}) map[string]interface{} {
  263. m.Open()
  264. defer m.Close()
  265. coll := m.C.Database(m.DbName).Collection(c)
  266. r := coll.FindOne(m.Ctx, query)
  267. v := map[string]interface{}{}
  268. r.Decode(&v)
  269. return v
  270. }
  271. //find
  272. func (m *MongodbSim) Find(c string, query map[string]interface{}, sort, fields interface{}) ([]map[string]interface{}, error) {
  273. m.Open()
  274. defer m.Close()
  275. coll := m.C.Database(m.DbName).Collection(c)
  276. op := options.Find()
  277. r, err := coll.Find(m.Ctx, query, op.SetSort(sort), op.SetProjection(fields))
  278. if err != nil {
  279. log.Fatal(err)
  280. return nil, err
  281. }
  282. var results []map[string]interface{}
  283. if err = r.All(m.Ctx, &results); err != nil {
  284. log.Fatal(err)
  285. return nil, err
  286. }
  287. return results, nil
  288. }
  289. //创建_id
  290. func NewObjectId() primitive.ObjectID {
  291. return primitive.NewObjectID()
  292. }
  293. func InitMgoEn(uri string, poolSize uint64,username_password ... string) (*Mgo, error) {
  294. //fengweiqiang fwq@123123
  295. m := Mgo{}
  296. m.Uri = uri
  297. if poolSize == 0 {
  298. m.PoolSize = 100
  299. }
  300. //fengweiqiang/fwq@123123
  301. options_client := options.Client().
  302. ApplyURI(uri).SetMaxPoolSize(m.PoolSize)
  303. if len(username_password)==2{
  304. options_client = options_client.SetAuth(options.Credential{Username: username_password[0], Password: username_password[1]})
  305. }
  306. client, err := mongo.Connect(context.Background(), options_client)
  307. if err != nil {
  308. return nil, err
  309. } else {
  310. m.mgoEn = client
  311. return &m, nil
  312. }
  313. }
  314. func (m *Mgo) GetCon() *mongo.Client {
  315. if m.mgoEn != nil {
  316. return m.mgoEn
  317. } else {
  318. return nil
  319. }
  320. }
  321. //var zwjeReg *regexp.Regexp = regexp.MustCompile(`([〇零点壹贰叁肆伍陆柒捌玖拾百佰千仟万萬亿億元圆角分整正]{4,40})`)