golang中使用mongo

來源:互聯網
上載者:User

筆者使用的mongo驅動是mgo, 這個使用的人比較多,文檔也比較齊全

  • 官網地址:http://labix.org/mgo
  • 文檔地址:https://godoc.org/labix.org/v2/mgo
  • 源碼地址:https://github.com/go-mgo/mgo

1. mgo包安裝

go get gopkg.in/mgo.v2

但是貌似現在從gopkg.in下載不了,迂迴一下,先從github上下載

go get github.com/go-mgo/mgo

下載好了之後,在$GOPATH/src/下面建立檔案夾gopkg.in/mgo.v2, 然後將github.com/go-mgo/mgo的內容,拷貝到gopkg.in/mgo.v2

2. 測試代碼

// 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:  "123456",        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 = 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())        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)    }}

這樣要注意的一點是 GameReport 裡面的欄位都要首字母大寫,否則不會寫入mongo

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.