diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..8152d8f --- /dev/null +++ b/go.mod @@ -0,0 +1,19 @@ +module myschools.me/suguo/mongo-sample + +go 1.19 + +require go.mongodb.org/mongo-driver v1.11.1 + +require ( + github.com/golang/snappy v0.0.1 // indirect + github.com/klauspost/compress v1.13.6 // indirect + github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe // indirect + github.com/pkg/errors v0.9.1 // indirect + github.com/xdg-go/pbkdf2 v1.0.0 // indirect + github.com/xdg-go/scram v1.1.1 // indirect + github.com/xdg-go/stringprep v1.0.3 // indirect + github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d // indirect + golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d // indirect + golang.org/x/sync v0.0.0-20210220032951-036812b2e83c // indirect + golang.org/x/text v0.3.7 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..56a2f76 --- /dev/null +++ b/go.sum @@ -0,0 +1,55 @@ +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/golang/snappy v0.0.1 h1:Qgr9rKW7uDUkrbSmQeiDsGa8SjGyCOGtuasMWwvp2P4= +github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/google/go-cmp v0.5.2 h1:X2ev0eStA3AbceY54o37/0PQ/UWqKEiiO2dKL5OPaFM= +github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/klauspost/compress v1.13.6 h1:P76CopJELS0TiO2mebmnzgWaajssP/EszplttgQxcgc= +github.com/klauspost/compress v1.13.6/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk= +github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe h1:iruDEfMl2E6fbMZ9s0scYfZQ84/6SPL6zC8ACM2oIL0= +github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe/go.mod h1:wL8QJuTMNUDYhXwkmfOly8iTdp5TEcJFWZD2D7SIkUc= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0= +github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/tidwall/pretty v1.0.0 h1:HsD+QiTn7sK6flMKIvNmpqz1qrpP3Ps6jOKIKMooyg4= +github.com/tidwall/pretty v1.0.0/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk= +github.com/xdg-go/pbkdf2 v1.0.0 h1:Su7DPu48wXMwC3bs7MCNG+z4FhcyEuz5dlvchbq0B0c= +github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI= +github.com/xdg-go/scram v1.1.1 h1:VOMT+81stJgXW3CpHyqHN3AXDYIMsx56mEFrB37Mb/E= +github.com/xdg-go/scram v1.1.1/go.mod h1:RaEWvsqvNKKvBPvcKeFjrG2cJqOkHTiyTpzz23ni57g= +github.com/xdg-go/stringprep v1.0.3 h1:kdwGpVNwPFtjs98xCGkHjQtGKh86rDcRZN17QEMCOIs= +github.com/xdg-go/stringprep v1.0.3/go.mod h1:W3f5j4i+9rC0kuIEJL0ky1VpHXQU3ocBgklLGvcBnW8= +github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d h1:splanxYIlg+5LfHAM6xpdFEAYOk8iySO56hMFq6uLyA= +github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d/go.mod h1:rHwXgn7JulP+udvsHwJoVG1YGAP6VLg4y9I5dyZdqmA= +go.mongodb.org/mongo-driver v1.11.1 h1:QP0znIRTuL0jf1oBQoAoM0C6ZJfBK4kx0Uumtv1A7w8= +go.mongodb.org/mongo-driver v1.11.1/go.mod h1:s7p5vEtfbeR1gYi6pnj3c3/urpbLv2T5Sfd6Rp2HBB8= +golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d h1:sK3txAijHtOK88l68nt020reeT1ZdKLIYetKl95FzVY= +golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= +golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/sync v0.0.0-20210220032951-036812b2e83c h1:5KslGYwFpkhGh+Q16bwMP3cOontH8FOep7tGV86Y7SQ= +golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/main.go b/main.go new file mode 100644 index 0000000..fd71a2a --- /dev/null +++ b/main.go @@ -0,0 +1,35 @@ +package main + +import ( + "fmt" + "log" + + "go.mongodb.org/mongo-driver/bson/primitive" + "myschools.me/suguo/mongo-sample/mongo" +) + +func main() { + mongo.Init(&mongo.Config{ + Uri: "mongodb://root:example@192.168.0.254:27017", + Database: "example", + Timeout: 10, + }) + + obj, err := mongo.DocumentCreate("person", &Student{ + ID: primitive.NewObjectID(), //ObjectID("000000000000000000000000"),重复插入出现E1100错误 + Name: "王保强", + Sex: "男", + }) + if err != nil { + log.Fatal(err) + } + + fmt.Println(obj) + +} + +type Student struct { + ID primitive.ObjectID `bson:"_id" json:"id,omitempty"` + Name string `json:"name,omitempty"` + Sex string `json:"sex,omitempty"` +} diff --git a/mongo/collection.go b/mongo/collection.go new file mode 100644 index 0000000..df3efc4 --- /dev/null +++ b/mongo/collection.go @@ -0,0 +1,9 @@ +package mongo + +import "go.mongodb.org/mongo-driver/mongo" + +// Collection 获取集合 +func Collection(client *mongo.Client, cname string) (*mongo.Collection, error) { + collection := client.Database(config.Database).Collection(cname) + return collection, nil +} diff --git a/mongo/config.go b/mongo/config.go new file mode 100644 index 0000000..574d1b0 --- /dev/null +++ b/mongo/config.go @@ -0,0 +1,9 @@ +package mongo + +type Config struct { + Uri string + Username string + Password string + Database string + Timeout int +} diff --git a/mongo/document.go b/mongo/document.go new file mode 100644 index 0000000..0b28aaa --- /dev/null +++ b/mongo/document.go @@ -0,0 +1,27 @@ +package mongo + +import ( + "context" + "time" +) + +// 文档创建,返回InsertedID +func DocumentCreate(colName string, obj interface{}) (interface{}, error) { + client, err := New() + if err != nil { + return nil, err + } + ctx, cancel := context.WithTimeout(context.Background(), time.Duration(config.Timeout)*time.Second) + defer cancel() + defer client.Disconnect(ctx) + col, err := Collection(client, colName) + if err != nil { + return nil, err + } + + ret, err := col.InsertOne(ctx, obj) + if err != nil { + return nil, err + } + return ret.InsertedID, nil +} diff --git a/mongo/mongo.go b/mongo/mongo.go new file mode 100644 index 0000000..229293a --- /dev/null +++ b/mongo/mongo.go @@ -0,0 +1,70 @@ +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" +) + +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()) +} + +// 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) + } +}