Go and MongoDB

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

Go does not have the concept of class, and the bundle of variables is implemented by the struct (struct) in the form of key-value pairs.
This is very friendly to MongoDB and JSON, which are also stored as key-value pairs. So in go, it is not very dependent on the ORM built on the MongoDB, the use of the lower driver-level interface can be easily operated.

This article will take the commodity (goods) as an example, briefly explain how to use MgO for simple additions and deletions to change the operation.

Mgo

MgO (pronounced as mango) is a MongoDB driver for the Go language that implements a rich and well Tested selection of features under a very simple API following standard Go idioms.

Open Terminal input

go get gopkg.in/mgo.v2

Create a new Goods.go file under the current Pkg and provide some encapsulation for the interfaces provided by MgO:

func connect(cName string) (*mgo.Session, *mgo.Collection) {    session, err := mgo.Dial("$mongoHost") //Mongodb's connection    if err != nil {        panic(err)    }    session.SetMode(mgo.Monotonic, true)    //return a instantiated collect    return session, session.DB(mongoDB).C(cName)}

To define a goods instance:

type Goods struct {    ID    string     Name  string     Price string     Url   string}

Next we will deposit the first record:

func (a *Goods) save() error {    s, c := connect("goods")    defer s.Close()    a.ID = bson.NewObjectId().Hex()    return c.Insert(&a)}

Special Note: If you define the type of the ID as defined bson.ObjectID , and specify the Bson label as _id , MongoDB will not assign it a new ID. But such a structure is not very convenient when interacting with JSON.

When making a record query, you need to create a new struct or struct array of the same type, and then perform Find the action, and if the argument is empty, return all records:

func (a Goods) all() ([]Goods, error) {    s, c := connect("goods")    defer s.Close()    var group []Goods    err := c.Find(nil).All(&group)    return group, err}
func (a *Goods) get(id string) error {    s, c := connect("goods")    defer s.Close()    return c.Find(bson.M{"id": id}).One(&a)}

If you are familiar with MONGODB operations, you can see that this is almost the same as working directly inside the shell.

Delete:

func (a Goods) delete() error {    s, c := connect("goods")    defer s.Close()    return c.Remove(bson.M{"id": a.ID})}

Update:

func (a *Goods) update() error {    s, c := connect("goods")    defer s.Close()    c.Update(bson.M{"id": a.ID}, a)    return a.get(a.ID)}

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.