{"id":16886175,"url":"https://github.com/yanue/mgo","last_synced_at":"2025-04-11T12:36:47.719Z","repository":{"id":57537354,"uuid":"285509911","full_name":"yanue/mgo","owner":"yanue","description":"基于mongo-driver封装的简化操作合集","archived":false,"fork":false,"pushed_at":"2024-10-17T08:39:43.000Z","size":51,"stargazers_count":4,"open_issues_count":0,"forks_count":3,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-03-25T08:51:22.365Z","etag":null,"topics":["mgo","mongo","mongo-driver-orm"],"latest_commit_sha":null,"homepage":"","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/yanue.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-08-06T07:57:54.000Z","updated_at":"2024-11-06T17:08:42.000Z","dependencies_parsed_at":"2025-02-19T10:46:09.043Z","dependency_job_id":null,"html_url":"https://github.com/yanue/mgo","commit_stats":null,"previous_names":[],"tags_count":4,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yanue%2Fmgo","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yanue%2Fmgo/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yanue%2Fmgo/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yanue%2Fmgo/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/yanue","download_url":"https://codeload.github.com/yanue/mgo/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248402385,"owners_count":21097328,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["mgo","mongo","mongo-driver-orm"],"created_at":"2024-10-13T16:38:34.168Z","updated_at":"2025-04-11T12:36:47.692Z","avatar_url":"https://github.com/yanue.png","language":"Go","funding_links":[],"categories":[],"sub_categories":[],"readme":"## 基于mongo-driver封装的简化操作合集\n\n### 安装:\n\n```\n    go get github.com/yanue/mgo\n```\n\n### 主要封装方法:\n\n```\ntype IMgo interface {\n\tGetMgoCli() *mongo.Client\n\tSetDbName(dbName string)\n\tGetDbName() string\n\tSetCollName(collName string)\n\tGetCollName() string\n\tGetCollection() *mongo.Collection\n\tGetLastId() int\n\tSetLastId(int)\n\tCount(where map[string]any) (cnt int64, err error)\n\tUpdate(id any, input map[string]any) error\n\tUpdateByMap(where map[string]any, input map[string]any) error\n\tCreate(item any) error\n\tSave(id any, item any) error\n\tInsertMany(item []any) error\n\tForceDelete(id any) error\n\tForceDeleteByMap(where map[string]any) error\n\tGetByField(result any, field string, val any) (err error)\n\tGetAllWithFields(results any, where map[string]any, _sort map[string]int, fields []string) (err error)\n\tGetOneByMap(result any, where map[string]any, sorts ...map[string]int) (err error)\n\tGetAllByMap(results any, where map[string]any, sorts ...map[string]int) (err error)\n\tList(results any, where map[string]any, page, size int, sorts ...map[string]int) (err error)\n\tListWithFields(results any, where map[string]any, page, size int, _sort map[string]int, fields []string) (err error)\n\tAggregate(pipeStr string, results any) error\n\tCreateIndex(keys bson.D, Unique bool) (string, error)\n\tDropIndex(name string) error\n}\n```\n\n### 第一步,初始化mongo连接\n\n```\n\tm, err := mgo.InitMongoClient(config.MongoUri,\"test\", 10)\n\tif err != nil {\n\t\tlog.Println(\"mongo连接失败:\", err.Error())\n\t\tos.Exit(0)\n\t}\n```\n\n### 第二步,新建model,继承Mgo\n\n```\n// 多库多表模式\nfunc newTestMultiModel(dbName, collName string) *testModel {\n\tm := new(testModel)\n\tm.Mgo.SetDbName(dbName)\n\tm.Mgo.SetCollName(collName)\n\treturn m\n}\n\n// 单例模式对外导出方法\nvar TestModel = newTestModel()\n\nfunc newTestModel() *testModel {\n\tm := new(testModel)\n\tm.Mgo.SetCollName(\"test\")\n\treturn m\n}\n\n// 表(集合)信息\ntype Test struct {\n\tId        int         `json:\"id\" bson:\"_id\"` // 自增涨id\n\tName      string      `json:\"name\" bson:\"name\"`\n\tAge       int         `json:\"age\" bson:\"age\"`\n\tData      interface{} `json:\"data\" bson:\"data\"`\n\tIsDeleted int         `json:\"is_deleted\" json:\"is_deleted\"`\n\tCreated   int         `json:\"created\" bson:\"created\"`\n}\n\n// 对mongo表操作处理\ntype testModel struct {\n\tMgo // 需要使用匿名结构,保证初始化不用单独new\n}\n\n// 通过单个字段查找数据\nfunc (model *testModel) GetByField(field string, val interface{}) (item *Test, err error) {\n\titem = new(Test)\n\terr = model.Mgo.GetByField(item, field, val)\n\treturn\n}\n\n// 通过多个字段map查询单个数据\nfunc (model *testModel) GetOneByMap(where map[string]interface{}, sorts ...map[string]int) (item *Test, err error) {\n\titem = new(Test)\n\terr = model.Mgo.GetOneByMap(item, where, sorts...)\n\treturn\n}\n\n// 通过多个字段map查询多条数据\nfunc (model *testModel) GetAllByMap(where map[string]interface{}, sorts ...map[string]int) (items []*Test, err error) {\n\titems = make([]*Test, 0)\n\terr = model.Mgo.GetAllByMap(\u0026items, where, sorts...)\n\treturn\n}\n\n// 根据id获取信息\nfunc (model *testModel) Get(id int) (*Test, error) {\n\treturn model.GetByField(\"_id\", id)\n}\n\n// 获取列表 - page从1开始\nfunc (model *testModel) List(where map[string]interface{}, page, size int, sorts ...map[string]int) (items []*Test, err error) {\n\titems = make([]*Test, 0)\n\terr = model.Mgo.List(\u0026items, where, page, size, sorts...)\n\treturn\n}\n\n// 创建\nfunc (model *testModel) Create(item *Test) (int, error) {\n\t// 自增获取id\n\titem.Id = model.GetLastId()\n\titem.Created = int(time.Now().Unix())\n\terr := model.Mgo.Create(item)\n\treturn item.Id, err\n}\n\n// 更新 - 通过map匹配字段\nfunc (model *testModel) Update(id int, input map[string]interface{}) error {\n\terr := model.Mgo.Update(id, input)\n\treturn err\n}\n\n// 更新 - 通过结构体 (!!注意!! 会以新数据覆盖)\nfunc (model *testModel) Save(data *Test) (err error) {\n\treturn model.Mgo.Save(data.Id, data)\n}\n\n// 软删\nfunc (model *testModel) Delete(id int) error {\n\treturn model.Update(id, map[string]interface{}{\"is_deleted\": 1})\n}\n\n// 硬删\nfunc (model *testModel) ForceDelete(id int) error {\n\treturn model.Mgo.ForceDelete(id)\n}\n\n// 聚合查询\nfunc (model *testModel) Aggregate(pipeStr string) (items []*Test, err error) {\n\titems = make([]*Test, 0)\n\terr = model.Mgo.Aggregate(pipeStr, \u0026items)\n\treturn\n}\n```\n\n### 第三步,使用model,测试\n\n```\n    _, err := InitMongoClient(\"mongodb://127.0.0.1:27017\", \"test\", 20)\n\tif err != nil {\n\t\tlog.Println(\"init mongo err: \", err.Error())\n\t\treturn\n\t}\n\t_, _ = TestModel.CreateIndex(bson.D{bson.E{Key: \"uid\", Value: -1}, bson.E{Key: \"account_id\", Value: -1}, bson.E{Key: \"period\", Value: -1}}, false)\n\t_, _ = TestModel.CreateIndex(bson.D{bson.E{Key: \"uid\", Value: -1}, bson.E{Key: \"period\", Value: -1}, bson.E{Key: \"account_id\", Value: -1}}, false)\n\tc := TestModel.DropIndex(\"name_1\")\n\tlog.Println(\"c\", c)\n\ta, b := TestModel.CreateIndex(bson.D{}, true)\n\tlog.Println(\"CreateIndex a, b\", a, b)\n\titem := \u0026Test{\n\t\tName: \"aaaaaaaaa\",\n\t\tData: map[string]interface{}{\"a\": 1, \"b\": 2},\n\t}\n\n\tid, err := TestModel.Create(item)\n\tlog.Println(\"id\", id, err)\n\n\terr = TestModel.Update(id, map[string]interface{}{\"age\": 18})\n\tlog.Println(\"update\", err)\n\n\trow, err := TestModel.Get(id)\n\tlog.Println(\"row\", row, err)\n\n\trow.Name = \"dddddddddddd\"\n\terr = TestModel.Save(row)\n\tlog.Println(\"Save\", row, err)\n\n\tlist, err := TestModel.GetAllByMap(map[string]interface{}{\"name\": \"ccccc\", \"age\": 28})\n\tlog.Println(\"list\", list, err)\n\n\t// 聚合查询\n\t//pipeline := `[\n\t//\t{\"$match\": { \"color\": \"Red\" }},\n\t//\t{\"$group\": { \"_id\": \"$brand\", \"count\": { \"$sum\": 1 } }},\n\t//\t{\"$project\": { \"brand\": \"$_id\", \"_id\": 0, \"count\": 1 }}\n\t//]`\n\tpipeline := `[\n\t\t{\"$match\": { \"name\": \"ccccc\" }}\n\t]`\n\titems, err := TestModel.Aggregate(pipeline)\n\tfmt.Println(\"items\", items, err)\n\tfor _, v := range items {\n\t\tfmt.Println(\"v\", *v)\n\t}\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyanue%2Fmgo","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fyanue%2Fmgo","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyanue%2Fmgo/lists"}