前言
筆者使用的mongo驅動是mgo, 這個使用的人比較多,文檔也比較齊全
官網地址:http://labix.org/mgo
文檔地址:https://godoc.org/labix.org/v2/mgo
源碼地址:https://github.com/go-mgo/mgo
1. mgo包安裝
1
|
go get gopkg. in /mgo .v2 |
但是貌似現在從gopkg.in下載不了,迂回一下,先從github上下載
1
|
go get github.com /go-mgo/mgo |
下載好了之后,在$GOPATH/src/下面創建文件夾gopkg.in/mgo.v2, 然后將github.com/go-mgo/mgo的內容,拷貝到gopkg.in/mgo.v2
2. 測試代碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
|
// mongo_test project main.go package main import ( "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
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對服務器之家的支持。
原文鏈接:https://studygolang.com/articles/14055