Operation classes using MongoDB in Golang and how to encapsulate

Source: Internet
Author: User
Tags mongodb connection string
This is a creation in Article, where the information may have evolved or changed.

About MgO

MongoDB officials do not have the drive to go MongoDB, so only use third-party drivers, MgO is the most used one.
MgO (sound mango) is a go language driver for MongoDB, which is rich in features and is well tested with a simple API based on Go syntax .

Official website: Http://labix.org/mgo

Document: Http://godoc.org/gopkg.in/mgo.v2

Installation and use

Installation

go get gopkg.in/mgo.v2

Use in Go

Package Mainimport ("Gopkg.in/mgo.v2", "Gopkg.in/mgo.v2/bson") type person struct {Id Bson. ObjectId ' Bson: "_id" ' Name string ' Bson: ' Tname ' '//bson: ' name ' indicates the corresponding field name in the MongoDB database phone string ' Bson: ' Tphon E "'}const URL =" 192.168.1.43:50000 "//mongodb connection string var (mgosession *mgo. Sessiondatabase = "MyDB")/** * Public method, gets session, if present, copies a copy of */func getsession () *mgo. Session {if mgosession = = Nil {var err errormgosession, err = MgO. Dial (URL) if err! = Nil {Panic (ERR)//Direct Terminator run}}//Max connection Chime think 4096return mgosession.clone ()}//public method, Get collection Object func Witchcollection (collection string, s func (*mgo). Collection) Error {session: = GetSession () defer session. Close () C: = Session. DB (dataBase). C (Collection) return S (c)}/** * Add Person Object */func Addperson (p person) string {p.id = Bson. Newobjectid () Query: = Func (c *mgo. Collection) Error {return C.insert (p)}err: = witchcollection ("person", query) if err! = Nil {return "false"}return P.id.hex ()}/** * Get a record via Objectid */func Getpersonbyid (ID string) *person {objid: = Bson. Objectidhex (ID) Person: = new (person) query: = Func (c *mgo. Collection) Error {return C.findid (ObjID). One (&person)}witchcollection ("person", query) return person}//get all the person data func Pageperson () []person {var Persons []personquery: = Func (c *mgo. Collection) Error {return C.find (nil). All (&persons)}err: = witchcollection ("person", query) if err! = Nil {return Persons}return persons}//update person data func Updateperson (Query Bson. M, change Bson. M) String {exop: = func (c *mgo. Collection) Error {return c.update (query, change)}err: = witchcollection ("person", EXOP) if err! = Nil {return "true"}retur N "false"}/** * Execute Query, this method can be split as public method * [Searchperson description] * @param {[type]} collectionname string [description] * @pa RAM {[Type]} query Bson. M [Description] * @param {[type]} sort Bson. M [Description] * @param {[Type]} fields Bson.      M [Description] * @param {[type]} skip int [description] * @param {[type]} limit int) (Results []interface{}, err error [description] */func Searchperson (collectionname string, query Bson. M, sort string, fields Bson. M, skip int, limit int) (Results []interface{}, err Error) {exop: = func (c *mgo. Collection) Error {return C.find (query). Sort (sort). Select (Fields). Skip (Skip). Limit (limit). All (&results)}err = Witchcollection (CollectionName, EXOP) return}

Explanatory notes

Connection string

The connection string can be used in MongoDB standard form

mongodb://myuser:mypass@localhost:40001,otherhost:40001/mydb

struct declaration

type Person struct {Id_   bson.ObjectId `bson:"_id"`Name  string        `bson:"tname"` //bson:"name" 表示mongodb数据库中对应的字段名称Phone string        `bson:"tphone"`}

Note that the first letter of the person's field is capitalized, otherwise it is not visible. by Bson: "Name" This way can define the field name of the collection in MongoDB, if not defined, MgO automatically put the first letter of the field name of the struct as the field name of the collection. If you do not need to get id_,id_ can not be defined, at the time of insertion will be automatically generated. However, the proposal is generated through the program, which can improve the efficiency of mongodb, or you can directly return Objectid after the insertion, for other programs to use

Create a Objecitid manually

bson.NewObjectId()//创建一个objectid

For more information, visit the Red Elephant ued

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.