mgo.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package mongo
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "gopkg.in/mgo.v2"
  7. "gopkg.in/mgo.v2/bson"
  8. )
  9. var Session *mgo.Session
  10. func MgoInit(addr string, username string, password string) error {
  11. var err error
  12. var session *mgo.Session
  13. if addr == "" {
  14. return errors.New("mongo init need addr")
  15. }
  16. if username == "" && password == "" {
  17. fmt.Printf("1:%v,%v,%v\n", addr, username, password)
  18. session, err = mgo.Dial(addr)
  19. } else {
  20. fmt.Printf("2:%v,%v,%v\n", addr, username, password)
  21. url := fmt.Sprintf("mongodb://%s:%s@%s", username, password, addr)
  22. session, err = mgo.Dial(url)
  23. }
  24. if err != nil {
  25. return err
  26. }
  27. Session = session
  28. return nil
  29. }
  30. func MgoSelectField(collection *mgo.Collection, filter interface{}, skip int, limit int, result interface{}, field ...string) error {
  31. var fields = bson.M{}
  32. for _, v := range field {
  33. fields[v] = 1
  34. }
  35. if limit == 0 {
  36. limit = 1000
  37. }
  38. query := collection.Find(filter).Select(fields)
  39. err := query.Skip(skip).Limit(limit).All(result)
  40. return err
  41. }
  42. func MgoSelectAllField(collection *mgo.Collection, filter interface{}, result interface{}, skip int, limit int, sort string) error {
  43. if limit == 0 {
  44. limit = 1000
  45. }
  46. query := collection.Find(filter)
  47. if sort == "" {
  48. return query.Skip(skip).Limit(limit).Sort("_id").All(result)
  49. }
  50. return query.Skip(skip).Limit(limit).Sort("_id").Sort(sort).All(result)
  51. }
  52. func MgoInsertMulti(collection *mgo.Collection, autoid bool, values ...interface{}) error {
  53. if autoid == false {
  54. return collection.Insert(values...)
  55. }
  56. insertValues := []interface{}{}
  57. for _, v := range values {
  58. bytes, _ := json.Marshal(v)
  59. tmp := map[string]interface{}{}
  60. json.Unmarshal(bytes, &tmp)
  61. delete(tmp, "_id")
  62. insertValues = append(insertValues, tmp)
  63. }
  64. return collection.Insert(insertValues...)
  65. }
  66. func MgoUpdateByIds(collection *mgo.Collection, ids []bson.ObjectId, set bson.M) error {
  67. if len(ids) == 0 {
  68. return nil
  69. }
  70. _, err := collection.UpdateAll(bson.M{"_id": bson.M{"$in": ids}}, bson.M{"$set": set})
  71. return err
  72. }
  73. func MgoUpdateAll(collection *mgo.Collection, selector interface{}, set interface{}) error {
  74. if count, _ := collection.Find(selector).Count(); count == 0 {
  75. return MgoInsertMulti(collection, true, set)
  76. }
  77. _, err := collection.UpdateAll(selector, bson.M{"$set": set})
  78. return err
  79. }