1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
| package common
import ( "context" "encoding/json" "errors" "time"
"go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" "gopkg.in/mgo.v2/bson" )
var ( MongoPool *MongoDb )
type MongoDb struct { connection *mongo.Collection }
func NewMongoDbPool() (*MongoDb, error) { pool, err := ConnectToDB() if err != nil { return nil, err } return &MongoDb{ connection: pool, }, nil }
func ConnectToDB() (*mongo.Collection, error) { url := "" name := "" collection := "" maxCollection := 10 var timeout time.Duration = 10 ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() o := options.Client().ApplyURI(url) o.SetMaxPoolSize(uint64(maxCollection)) client, err := mongo.Connect(ctx, o) if err != nil { return nil, err } return client.Database(name).Collection(collection), nil }
func (m *MongoDb) jsonStr2Bson(str string) (interface{}, error) { var want interface{} err := bson.UnmarshalJSON([]byte(str), &want) if err != nil { return nil, err } return want, nil }
func (m *MongoDb) InsertToDb(wantStr string) (string, error) { if wantStr == "" { return "", errors.New("转换的字符串为空") } want, err := m.jsonStr2Bson(wantStr) if err != nil { return "", err } res, err := m.connection.InsertOne(context.TODO(), want) if err != nil { return "", err } id, ok := res.InsertedID.(primitive.ObjectID) if !ok { return "", errors.New("断言错误") } return id.Hex(), nil }
func (m *MongoDb) FindInfoByField(field, want string) (string, error) { ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() filter := bson.M{field: want} cursor, err := m.connection.Find(ctx, filter) if err != nil { return "", err } defer cursor.Close(ctx) var temp []bson.M if err = cursor.All(context.Background(), &temp); err != nil { return "", err } if len(temp) == 0 { return "", nil } jsonInfo, err := json.Marshal(temp) if err != nil { return "", err } return string(jsonInfo), nil }
func (m *MongoDb) FindInfoById(id string) (string, error) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() objID, _ := primitive.ObjectIDFromHex(id) filter := bson.M{"_id": objID} cursor, err := m.connection.Find(ctx, filter) if err != nil { return "", err } defer cursor.Close(ctx) var temp []bson.M if err = cursor.All(context.Background(), &temp); err != nil { return "", err } if len(temp) == 0 { return "", nil } jsonInfo, err := json.Marshal(temp[0]) if err != nil { return "", err } return string(jsonInfo), nil }
|