This is a creation in Article, where the information may have evolved or changed.
Communication with MongoDB in go language-using MgO
Category: MongoDB 2013-08-28 15:52 1585 people read Comments (0) Collection Report
Recently wrote a game suit. It's all new. Go language +mongodb. Hey. about how MgO is used is not detailed. The official website is very clear. This piece is about how to use it.
Import the MgO library first.
Import (
"Labix.org/v2/mgo"
"Labix.org/v2/mgo/bson"
)
Declaring DB
var Db_dbs *mgo. Database
Statement Collection
var db_dbuserlist *mgo. Collection
Connecting to a database
Session, Err: = MgO. Dial ("127.0.0.1")
Select the DB for use
Db_dbs = Session. DB ("Jltx")
Select the corresponding collection
Db_dbuserlist = Db_dbs. C ("UserList")
That's it. You can get into the table operation. Read the MONGO authoritative guide. You just have to be a shell. Communicating with MgO to the DB will be simple.
Bson. m{} This thing is the star of the whole MgO dong. Used to turn the structure of Golang Bson.
For example, to find all the data in the info table
[CPP]View Plaincopy
- INFs: = []dbinfo{}
- Err = Db_dbinfo.find (&bson. m{}). All (&INFS)
The corresponding shell should be: Db.dbinfo.find () return all information
For example: First find all the collections where name is Enel
[CPP]View Plaincopy
- //Find Users
- var u DBUser
- US := []DBUSER{}  
- ERR: = Db_dbuserlist.find (&bson. m{"Name": "Enel"}). All (&us)
The corresponding shell should be. Db.userlist.find ({"Name": "Enel0"}) returns the combination of hits
The above two examples are easy to see Bson. m{} and the shell's notation. Use good Bson. m{} will be able to use a good mongodb.
Here's an insert operation.
You can create a struct in go. Insert inside. Very simple.
[CPP]View Plaincopy
- U = Dbuser{bson. Newobjectid (), Binf. Uuiduser, CSName, Cspassword, Uint8 (Cssex)}
- Db_dbuserlist.insert (&u)