首先通过go get 安装mongo的依赖库
server1.example.com 更改为你MongoDB的IP地址
1 |
go get gopkg.in/mgo.v2 |
Example:
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 |
package main import ( "fmt" "log" "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" ) type Person struct { Name string Phone string } func main() { session, err := mgo.Dial("server1.example.com,server2.example.com") if err != nil { panic(err) } defer session.Close() // Optional. Switch the session to a monotonic behavior. session.SetMode(mgo.Monotonic, true) c := session.DB("test").C("people") err = c.Insert(&Person{"Ale", "+55 53 8116 9639"}, &Person{"Cla", "+55 53 8402 8510"}) if err != nil { log.Fatal(err) } result := Person{} err = c.Find(bson.M{"name": "Ale"}).One(&result) if err != nil { log.Fatal(err) } fmt.Println("Phone:", result.Phone) } |
Go 语言使用Mongodb开发Demo
有疑问加站长微信联系(非本文作者)