How to use mongo in golang is described

  • 2020-06-15 09:17:34
  • OfStack


The mongo driver used by the author is mgo, which is used by more people and the documents are 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

But it seems that you can't download it from, so I'll take a detour and download it from github first

go get

After download good, create the folder below $GOPATH src/gopkg. in/mgo v2, then github. com/go - mgo/mgo content, copy to gopkg. in/mgo v2

2. Test code

// mongo_test project main.go
package main

import (


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

func main() {
 dail_info := &mgo.DialInfo{
  Addrs:  []string{""},
  Direct: false,
  Timeout: time.Second * 1,
  Database: "game_report",
  Source: "admin",
  Username: "test1",
  Password: "123456",
  PoolLimit: 1024,

 session, err := mgo.DialWithInfo(dail_info)
 if err != nil {
  fmt.Printf("mgo dail error[%s]\n", err.Error())

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

 result := GameReport{}
 var to_find_game_id int64 = 100
 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())

 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",

 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)

One thing to note about GameReport is that all fields in GameReport should be capitalized, otherwise mongo would not be written


Related articles: