This is a creation in Article, where the information may have evolved or changed.
Original: http://blog.sina.com.cn/s/blog_4d8cf3140101mt6y.html
MgO Usage Guide
About MgO
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.
GOLANG.TC (golangtc.com) Web site data storage is the use of Mongodb+mgo. Used to perform well in the past year.
API documentation
Below are the online documentation for MGO, Mgo/bson, Mgo/txn.
MgO Godoc Gowalker
Mgo/bson Godoc Gowalker
Mgo/txn Godoc Gowalker
Installation
Please install Golang and MongoDB before installing MGO, the installation process will not repeat.
Install the BZR version tool (MgO uses Bazaar as the version control system, as the installation needs to go to the bazaar to replace the code).
Installation commands
Go get Labix.org/v2/mgo
Example
The following code is an example.
Package main import ("FMT" "Labix.org/v2/mgo" "Labix.org/v2/mgo/bson") type person struct {Name string Phone string} F UNC Main () {session, Err: = MgO. Dial ("") if err! = Nil {panic (ERR)} defer session. Close ()//Optional. Switch the session to a monotonic behavior. Session. SetMode (MgO. Monotonic, True) c: = Session. DB ("Test"). C ("people") Err = C.insert (&person{"Ale", "+55 8116 9639"}, &person{"Cla", "+55" 8402 8510 "}) if err! = Nil { Panic (ERR)} Result: = person{} err = C.find (Bson. m{"name": "Ale"}). One (&result) if err! = Nil {panic (err)} FMT. Println ("Phone:", result.) Phone)}
Start MongoDB, copy the above code to run, if the output below, indicating the installation is successful.
Phone: +55 53 8116 9639
What does the code mean first without the tube, and the use of each method is explained later.
How to use
The following describes how to use MgO, which mainly describes the operation of the collection. For the database, users, etc., please view the document yourself.
The first step of course is to import the MgO package first
Import ("Labix.org/v2/mgo" "Labix.org/v2/mgo/bson")
Connecting to a server
Use method dial () to establish a connection to the MongoDB server. Dial () is defined as follows:
Func Dial (URL string) (*session, error)
Specific use:
Session, Err: = MgO. Dial (URL)
If this is the case, and MongoDB is the default port 27017 startup, here are a few ways to do it.
Session, Err: = MgO. Dial ("") session, Err: = MgO. Dial ("localhost") session, Err: = MgO. Dial ("127.0.0.1") session, Err: = MgO. Dial ("localhost:27017") session, Err: = MgO. Dial ("127.0.0.1:27017")
If you are not on a different computer or port, pass in the appropriate address. Such as:
Mongodb://myuser:mypass@localhost:40001,otherhost:40001/mydb
Switch database
Switch to the appropriate database by Session.db ().
Func (S *session) DB (name string) *database
such as switching to the test database.
DB: = Session. DB ("Test")
Toggle Collection
The Database.c () method is used to switch the set (Collection) so that we can make additions and deletions to the collection.
Func (db *database) C (name string) *collection
such as switching to the ' users ' collection.
c: = db. C ("Users")
To manipulate a collection
Describes insert, query, modify, delete operations.
Just mention it. Objectid,mongodb Each collection will have a primary key named _id, which is a 24-bit 16 binary string. The corresponding to the MgO is Bson. ObjectId.
Here we define a struct, which corresponds to the set.
Type User struct {id_ Bson. ObjectId ' Bson: "_id" ' Name string ' Bson: ' name ' ' Age int ' Bson: ' Age ' ' Jonedat time. Time ' Bson: "joned_at" ' interests []string ' Bson: ' Interests '}
Annotations
Note that the first letter of the user'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.
Insert
The Insert method is defined as follows:
Func (c *collection) Insert (Docs ... interface{}) error
The following code inserts two collection data.
Err = C.insert (&user{id_: Bson. Newobjectid (), Name: "Jimmy kuu", age:33, Joinedat:time. Now (), Interests: []string{"Develop", "Movie"},}) if err! = Nil {panic (err)} err = C.insert (&user{id_: Bson. Newobjectid (), Name: "Tracy Yu", age:31, Joinedat:time. Now (), Interests: []string{"shoping", "TV"},}) if err! = Nil {panic (err)}
Here through the Bson. Newobjectid () to create a new objectid, if you need to use it, put it in a variable, generally in web development can be used as parameters to jump to other pages.
Through the MongoDB client can be found, two is already inserted.
{"_id": ObjectId ("5204af979955496907000001"), "name": "Jimmy Kuu", "Age":, "Joned_at": Date (1376038807950), "I Nterests ": [" Develop "," Movie "]} {" _id ": ObjectId (" 5204af979955496907000002 ")," name ":" Tracy Yu "," age ": +," j Oned_at ": Date (1376038807971)," interests ": [" shoping "," TV "]}
Inquire
With the Func (C *collection) Find (Query interface{}) *query, the returned query struct can be filtered with various conditions attached.
All results can be obtained through Query.all (), and a result can be obtained through query.one (), noting that if there is no data or more than one, the first one () will error.
Conditions with Bson. M{key:value}, note that key must use the field name in MongoDB, not the field name of the struct.
Unconditional Query
Query all
var users []user C.find (nil). All (&users) fmt. Println (Users)
The above code can identify all users:
[{Objectidhex ("5204af979955496907000001") Jimmy kuu 2013-08-09 17:00:07.95 +0800 CST [Develop Movie]} {Objectidhex (" 5204af979955496907000002 ") Tracy Yu 2013-08-09 17:00:07.971 +0800 CST [shoping TV]}]
Query based on Objectid
ID: = "5204af979955496907000001" objectId: = Bson. Objectidhex (ID) User: = new (user) C.find (Bson. m{"_id": ObjectId}). One (&user) fmt. PRINTLN (user)
The results are as follows:
&{objectidhex ("5204af979955496907000001") Jimmy kuu 2013-08-09 17:00:07.95 +0800 CST [Develop Movie]}
The simpler way is to use the Findid () method directly:
C.findid (objectId). One (&user)
Annotations
Note that err is not handled here. Using the One () method will make an error when it cannot be found.
Single-Condition Query
= ($EQ)
C.find (Bson. m{"name": "Jimmy Kuu"}). All (&users)
! = ($ne)
C.find (Bson. m{"name": Bson. m{"$ne": "Jimmy Kuu"}}). All (&users)
> ($GT)
C.find (Bson. M{"Age": Bson. m{"$GT": 32}}). All (&users)
< ($LT)
C.find (Bson. M{"Age": Bson. m{"$lt": 32}}). All (&users)
>= ($GTE)
C.find (Bson. M{"Age": Bson. m{"$gte": 33}}). All (&users)
<= ($lte)
C.find (Bson. M{"Age": Bson. m{"$lte": 31}}). All (&users)
In ($in)
C.find (Bson. m{"name": Bson. m{"$in": []string{"Jimmy Kuu", "Tracy Yu"}}). All (&users)
Multi-Criteria Query
and ($and)
C.find (Bson. m{"name": "Jimmy Kuu", "Age": 33}). All (&users)
or ($or)
C.find (Bson. m{"$or": []bson. M{bson. m{"name": "Jimmy Kuu"}, Bson. M{"Age": 31}}). All (&users)
Modify
The modify operation is made through the Func (*collection) update.
Func (c *collection) Update (selector interface{}, change interface{}) error
Note that modifying single or multiple fields requires a $set action symbol, or the collection is replaced.
Modify the value of a field ($set)
C.update (Bson. m{"_id": Bson. Objectidhex ("5204af979955496907000001")}, Bson. m{"$set": Bson. m{"name": "Jimmy Gu", "age": 34,}})
Inc ($INC)
Field Increment value
C.update (Bson. m{"_id": Bson. Objectidhex ("5204af979955496907000001")}, Bson. m{"$inc": Bson. M{"Age":-1,}})
Push ($push)
Add an element from the array
C.update (Bson. m{"_id": Bson. Objectidhex ("5204af979955496907000001")}, Bson. m{"$push": Bson. m{"Interests": "Golang",}})
Pull ($pull)
Remove an element from an array
C.update (Bson. m{"_id": Bson. Objectidhex ("5204af979955496907000001")}, Bson. m{"$pull": Bson. m{"Interests": "Golang",}})
Delete
C.remove (Bson. m{"name": "Jimmy Kuu"})
It also supports multi-criteria, referencing multi-conditional queries.