Go and mongodb


Go does not have the concept of class, and the binding of variables is implemented by structs in the form of key value pairs.
This is very friendly to mongodb and JSON, which are also stored as key value pairs. Therefore, in go, the ORM based on mongodb is not very dependent. It can be operated easily by using the interface of the lower driver level.

This article will take goods as an example to briefly explain how to use MgO for simple addition, deletion, modification and query.


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 to encapsulate the interfaces provided by MgO:

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

Define the goods instance:

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

Next, we will save 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 attention:If the type of ID is defined asbson.ObjectID, and specify the bson label as_id, mongodb will not assign it a new ID. However, such a structure is not very convenient when interacting with JSON.

When querying records, you need to create a new structure or structure array of the same type, and then executeFindOperation. If the parameter is empty, all records will be returned:

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 the operation of mongodb, you can see that this operation is almost the same as operating directly in the shell.


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

to 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)