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