From 5903333242735c681455cf29f13350f297f22fc8 Mon Sep 17 00:00:00 2001 From: "suguo.yao" Date: Sun, 14 Nov 2021 19:07:38 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0mongo=E6=94=AF=E6=8C=81?= =?UTF-8?q?=E5=8F=8A=E7=9B=B8=E5=85=B3test?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- go.mod | 10 +++ mongo/mongo.go | 84 ++++++++++++++++++++++++ mongo/mongo_test.go | 151 ++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 245 insertions(+) create mode 100644 mongo/mongo.go create mode 100644 mongo/mongo_test.go diff --git a/go.mod b/go.mod index 0815bd9..b943cf5 100644 --- a/go.mod +++ b/go.mod @@ -22,7 +22,9 @@ require ( github.com/go-playground/universal-translator v0.17.0 // indirect github.com/go-playground/validator/v10 v10.4.1 // indirect github.com/go-sql-driver/mysql v1.6.0 // indirect + github.com/go-stack/stack v1.8.0 // indirect github.com/golang/protobuf v1.5.2 // indirect + github.com/golang/snappy v0.0.1 // indirect github.com/grpc-ecosystem/grpc-gateway/v2 v2.6.0 // indirect github.com/hashicorp/go-cleanhttp v0.5.1 // indirect github.com/hashicorp/go-hclog v0.12.0 // indirect @@ -33,6 +35,7 @@ require ( github.com/jinzhu/inflection v1.0.0 // indirect github.com/jinzhu/now v1.1.2 // indirect github.com/json-iterator/go v1.1.11 // indirect + github.com/klauspost/compress v1.13.6 // indirect github.com/kr/text v0.2.0 // indirect github.com/leodido/go-urn v1.2.0 // indirect github.com/mattn/go-colorable v0.1.6 // indirect @@ -43,10 +46,17 @@ require ( github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.1 // indirect github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e // indirect + github.com/pkg/errors v0.9.1 // indirect github.com/stretchr/testify v1.7.0 // indirect github.com/ugorji/go/codec v1.1.13 // indirect + github.com/xdg-go/pbkdf2 v1.0.0 // indirect + github.com/xdg-go/scram v1.0.2 // indirect + github.com/xdg-go/stringprep v1.0.2 // indirect + github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d // indirect + go.mongodb.org/mongo-driver v1.7.4 // indirect golang.org/x/crypto v0.0.0-20201221181555-eec23a3978ad // indirect golang.org/x/net v0.0.0-20210813160813-60bc85c4be6d // indirect + golang.org/x/sync v0.0.0-20210220032951-036812b2e83c // indirect golang.org/x/sys v0.0.0-20210823070655-63515b42dcdf // indirect golang.org/x/text v0.3.7 // indirect google.golang.org/genproto v0.0.0-20210903162649-d08c68adba83 // indirect diff --git a/mongo/mongo.go b/mongo/mongo.go new file mode 100644 index 0000000..1128728 --- /dev/null +++ b/mongo/mongo.go @@ -0,0 +1,84 @@ +package mongo + +import ( + "context" + "errors" + "strings" + "time" + + "go.mongodb.org/mongo-driver/mongo" + "go.mongodb.org/mongo-driver/mongo/options" + "go.mongodb.org/mongo-driver/mongo/readpref" +) + +type Config struct { + Uri string + Username string + Password string + Database string + Timeout int +} + +var config *Config + +func Init(conf *Config) { + config = conf + if config == nil { + config = &Config{ + Uri: "mongodb://localhost:27017", + Database: "admin", + Timeout: 3, + } + } +} + +//New 获取mongo客户端 +//// "mongodb://user:password@localhost:27017" +func New() (*mongo.Client, error) { + clientOpts := options.Client().ApplyURI(config.Uri) + + if config.Username != "" && config.Password != "" { + clientOpts = clientOpts.SetAuth(options.Credential{ + AuthMechanism: "SCRAM-SHA-256", + AuthSource: config.Database, + Username: config.Username, + Password: config.Password, + }) + } + + ctx, cancel := context.WithTimeout(context.Background(), time.Duration(config.Timeout)*time.Second) + defer cancel() + + return mongo.Connect(ctx, clientOpts) +} + +func Ping() error { + client, err := New() + if err != nil { + return err + } + ctx, cancel := context.WithTimeout(context.Background(), time.Duration(config.Timeout)*time.Second) + defer cancel() + defer client.Disconnect(ctx) + return client.Ping(ctx, readpref.Primary()) +} + +//Collection 获取集合 +func Collection(client *mongo.Client, cname string) (*mongo.Collection, error) { + collection := client.Database(config.Database).Collection(cname) + return collection, nil +} + +//CollectionMulti 支持多数据库直接获取collection +func CollectionMulti(client *mongo.Client, cname string) (*mongo.Collection, error) { + name := strings.Split(cname, ".") + if len(name) != 2 { + return nil, errors.New("collection名称不正确,请使用[database.collection]方式使用") + } + if name[0] == "" || name[1] == "" { + return nil, errors.New("名称不能为空") + } + + collection := client.Database(name[0]).Collection(name[1]) + return collection, nil +} diff --git a/mongo/mongo_test.go b/mongo/mongo_test.go new file mode 100644 index 0000000..cbb9201 --- /dev/null +++ b/mongo/mongo_test.go @@ -0,0 +1,151 @@ +package mongo + +import ( + "context" + "fmt" + "testing" + "time" + + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/mongo" +) + +func init() { + Init(&Config{ + Uri: "mongodb://192.168.0.254:27017", + Database: "test", + Username: "test", + Password: "Test1231", + Timeout: 3, + }) +} + +func TestMongo(t *testing.T) { + if err := Ping(); err != nil { + t.Fatal(err) + } +} + +type Student struct { + ID primitive.ObjectID `bson:"_id" json:"id,omitempty"` + Name string `json:"name,omitempty"` + Sex string `json:"sex,omitempty"` +} + +func TestInsert(t *testing.T) { + client, err := New() + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + defer client.Disconnect(ctx) + col, err := Collection(client, "student") + if err != nil { + t.Fatal(err) + } + // ret, err := col.InsertOne(ctx, Student{Name: "张惠", Sex: "女"}) + ret, err := col.InsertOne(ctx, Student{ID: primitive.NewObjectID(), Name: "张惠", Sex: "女"}) + if err != nil { + t.Fatal(err) + } + fmt.Println(ret) +} + +func TestDelete(t *testing.T) { + client, err := New() + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + defer client.Disconnect(ctx) + col, err := Collection(client, "student") + if err != nil { + t.Fatal(err) + } + if err := col.FindOneAndDelete(ctx, bson.D{{"name", "张惠"}}).Err(); err != nil { + t.Fatal(err) + } +} + +func TestSingleResult(t *testing.T) { + client, err := New() + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + defer client.Disconnect(ctx) + col, err := Collection(client, "student") + if err != nil { + t.Fatal(err) + } + var result Student + // if err := col.FindOne(ctx, bson.D{{"name", "张惠"}}).Decode(&result); err != nil { + if err := col.FindOne(ctx, bson.M{"name": "张惠"}).Decode(&result); err != nil { + if err != mongo.ErrNoDocuments { + t.Fatal(err) + } + } + fmt.Println(result) +} + +func TestFindAll(t *testing.T) { + client, err := New() + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + defer client.Disconnect(ctx) + col, err := Collection(client, "student") + if err != nil { + t.Fatal(err) + } + cur, err := col.Find(ctx, bson.D{}) + if err != nil { + t.Fatal(err) + } + defer cur.Close(ctx) + for cur.Next(ctx) { + var result Student + if err := cur.Decode(&result); err != nil { + t.Fatal(err) + } + fmt.Println(result, result.ID.String(), result.ID.Timestamp(), result.ID.Timestamp().Local()) + } + if err := cur.Err(); err != nil { + t.Fatal(err) + } +} + +func TestFind(t *testing.T) { + client, err := New() + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + defer client.Disconnect(ctx) + col, err := Collection(client, "student") + if err != nil { + t.Fatal(err) + } + cur, err := col.Find(ctx, bson.M{"name": bson.M{"$ne": "张惠"}}) //注意这里的格式$ne不相等,$gt大于,$gte大于等于,$in in,$nin no in ,$exists是否包含这个键... + if err != nil { + t.Fatal(err) + } + defer cur.Close(ctx) + for cur.Next(ctx) { + var result Student + if err := cur.Decode(&result); err != nil { + t.Fatal(err) + } + fmt.Println(result, result.ID.String(), result.ID.Timestamp(), result.ID.Timestamp().Local()) + } + if err := cur.Err(); err != nil { + t.Fatal(err) + } +}