The author uses the MONGO drive is MgO, this use more people, the document is also quite complete
- Website address: Http://labix.org/mgo
- Document Address: Https://godoc.org/labix.org/v2/mgo
- Source Address: Https://github.com/go-mgo/mgo
1. MgO Package Installation
go get gopkg.in/mgo.v2
But it looks like it's not going to be downloaded from gopkg.in, just a detour, download it from GitHub.
go get github.com/go-mgo/mgo
After the download is done, create the folder Gopkg.in/mgo.v2 under $gopath/src/, and then copy the Github.com/go-mgo/mgo contents to the Gopkg.in/mgo.v2
2. Test code
Mongo_test Project Main.gopackage mainimport ("FMT" "Math/rand" "Time" "Gopkg.in/mgo.v2" "Gopkg.in/mgo". V2/bson ") type gamereport struct {//ID Bson. ObjectId ' Bson: "_id" ' game_id Int64 game_length int64 game_map_id string}func Err_handler (err error) {FMT . Printf ("Err_handler, error:%s\n", err. Error ()) Panic (err. Error ())}func main () {dail_info: = &mgo. dialinfo{Addrs: []string{"127.0.0.1"}, Direct:false, Timeout:time. Second * 1, Database: "Game_report", Source: "admin", Username: "Test1", Password: "1234 POOLLIMIT:1024,} session, Err: = MgO. Dialwithinfo (dail_info) if err! = Nil {fmt. Printf ("MgO dail error[%s]\n", err. Error ()) Err_handler (ERR)} defer session. Clone ()//Set mode session. SetMode (MgO. Monotonic, True) c: = Session. DB ("Game_report"). C ("Game_detail_report") r: = Rand. New (Rand. Newsource (time. Now (). UnixNano ()) Report: = gamereport{//Id:bson. Newobjectid (), game_id:100, game_length:r.int63 ()% 3600, game_map_id: "Hello",} err = C . Insert (report) if err! = Nil {fmt. Printf ("Try Insert record error[%s]\n", err.) Error ()) Err_handler (ERR)} Result: = gamereport{} var to_find_game_id int64 = + Err = C.find (Bson. m{"game_id": to_find_game_id}). One (&result) if err! = Nil {fmt. Printf ("Try Find record error[%s]\n", err.) Error ()) Err_handler (Err)} FMT. Printf ("res, game_id[%d] length[%d] game_map_id[%s]\n", to_find_game_id, result. Game_length, result. game_map_id)//Try Find all report var results []gamereport err = C.find (Bson. m{}). All (&results) if err! = Nil {fmt. Printf ("Try game all record of Game_detail_report error[%s]\n", err. Error ()) Err_handler (Err)} Result_count: = Len (results) fmt. Printf ("Result count:%d\n", Result_cOunt) for I, Report: = Range Results {FMT. Printf ("Index:%d, report{game_id:%d, game_length:%d, game_map_id:%s}\n", I, report. game_id, report. Game_length, report. GAME_MAP_ID)}}
It is important to note that the fields inside the Gamereport are capitalized first, otherwise they will not be written to MONGO