Golang a simple package for MongoDB operation

Source: Internet
Author: User
Tags findone

Golang a simple package for MongoDB operation

Use MongoDB the Go Drive library MgO, MongoDB do a simple package for the operation

Initialization

    • The operation does not have user rightsMongoDB
var globalS *mgo.Sessionfunc init() {    s, err := mgo.Dial(dialInfo)    if err != nil {        log.Fatalf("Create Session: %s\n", err)    }    globalS = s}
    • If you MongoDB set the user rights, you need to use the following method:
func init() {    dialInfo := &mgo.DialInfo{        Addrs:     []string{dbhost}, //数据库地址 dbhost: mongodb://user@123456:127.0.0.1:27017        Timeout:   timeout,                  // 连接超时时间 timeout: 60 * time.Second        Source:    authdb,                   // 设置权限的数据库 authdb: admin        Username:  authuser,                 // 设置的用户名 authuser: user        Password:  authpass,                // 设置的密码 authpass: 123456        PoolLimit: poollimit,       // 连接池的数量 poollimit: 100    }    s, err := mgo.DialWithInfo(dialInfo)    if err != nil {        log.Fatalf("Create Session: %s\n", err)    }    globalS = s}

Connect to specific data and documents

Copy each operation Session to avoid each creation Session , causing the number of connections to exceed the maximum value set
Get Document Objectc := Session.DB(db).C(collection)

func connect(db, collection string) (*mgo.Session, *mgo.Collection) {    ms := globalS.Copy()    c := ms.DB(db).C(collection)    ms.SetMode(mgo.Monotonic, true)    return ms, c}

Inserting data

Active shutdown Session defer Session.Close() after each operation
DB: Operational database
Collection: operational documentation (table)
Doc: Data to insert

func Insert(db, collection string, doc interface{}) error {    ms, c := connect(db, collection)    defer ms.Close()    return c.Insert(doc)}// testdata := &Data{    Id:      bson.NewObjectId().Hex(),    Title:   "标题",    Des:     "博客描述信息",    Content: "博客的内容信息",    Img:     "https://upload-images.jianshu.io/upload_images/8679037-67456031925afca6.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/700",    Date:    time.Now(),}err := db.Insert("Test", "TestModel", data)

Querying data

DB: Operational database
Collection: operational documentation (table)
Query: Search criteria
Selector: Data that needs to be filtered (projection)
Result: The results of the query

func FindOne(db, collection string, query, selector, result interface{}) error {    ms, c := connect(db, collection)    defer ms.Close()    return c.Find(query).Select(selector).One(result)}func FindAll(db, collection string, query, selector, result interface{}) error {    ms, c := connect(db, collection)    defer ms.Close()    return c.Find(query).Select(selector).All(result)}//test 查询title="标题",并且返回结果中去除`_id`字段var result Dataerr = db.FindOne(database, collection, bson.M{"title": "标题"}, bson.M{"_id":0}, &result)

Update data

DB: Operational database
Collection: operational documentation (table)
Selector: Update condition
Update: An updated operation

func Update(db, collection string, selector, update interface{}) error {    ms, c := connect(db, collection)    defer ms.Close()    return c.Update(selector, update)}//更新,如果不存在就插入一个新的数据 `upsert:true`func Upsert(db, collection string, selector, update interface{}) error {    ms, c := connect(db, collection)    defer ms.Close()    _, err := c.Upsert(selector, update)    return err}// `multi:true`func UpdateAll(db, collection string, selector, update interface{}) error {    ms, c := connect(db, collection)    defer ms.Close()    _, err := c.UpdateAll(selector, update)    return err}//testerr = db.Update(database, collection, bson.M{"_id": "5b3c30639d5e3e24b8786540"}, bson.M{"$set": bson.M{"title": "更新标题"}})

Delete data

DB: Operational database
Collection: operational documentation (table)
Selector: Delete condition

func Remove(db, collection string, selector interface{}) error {    ms, c := connect(db, collection)    defer ms.Close()    return c.Remove(selector)}func RemoveAll(db, collection string, selector interface{}) error {    ms, c := connect(db, collection)    defer ms.Close()    _, err := c.RemoveAll(selector)    return err}//testerr = db.Remove(database,collection,bson.M{"_id":"5b3c30639d5e3e24b8786540"})

Paging Query

DB: Operational database
Collection: operational documentation (table)
Page: Current pages
Limit: Number of values per page
Query: Search criteria
Selector: Data that needs to be filtered (projection)
Result: The results of the query

func FindPage(db, collection string, page, limit int, query, selector, result interface{}) error {    ms, c := connect(db, collection)    defer ms.Close()    return c.Find(query).Select(selector).Skip(page * limit).Limit(limit).All(result)}

Other operations

func IsEmpty(db, collection string) bool {    ms, c := connect(db, collection)    defer ms.Close()    count, err := c.Count()    if err != nil {        log.Fatal(err)    }    return count == 0}func Count(db, collection string, query interface{}) (int, error) {    ms, c := connect(db, collection)    defer ms.Close()    return c.Find(query).Count()}

Please refer to the complete code

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.