這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
使用mgo http://godoc.org/labix.org/v2/mgo
package mainimport ( "fmt" "labix.org/v2/mgo" "labix.org/v2/mgo/bson")type Person struct { NAME string PHONE string}type Men struct { Persons []Person}const = ( URL = "192.168.2.175:27017")func main() { session, err := mgo.Dial(URL) //串連資料庫 if err != nil { panic(err) } defer session.Close() session.SetMode(mgo.Monotonic, true) db := session.DB("mydb") //資料庫名稱 collection := db.C("person") //如果該集合已經存在的話,則直接返回 //*****集合中元素數目******** countNum, err := collection.Count() if err != nil { panic(err) } fmt.Println("Things objects count: ", countNum) //*******插入元素******* temp := &Person{ PHONE: "18811577546", NAME: "zhangzheHero" } //一次可以插入多個對象 插入兩個Person對象 err = collection.Insert(&Person{"Ale", "+55 53 8116 9639"}, temp) if err != nil { panic(err) } //*****查詢單條資料******* result := Person{} err = collection.Find(bson.M{"phone": "456"}).One(&result) fmt.Println("Phone:", result.NAME, result.PHONE) //*****查詢多條資料******* var personAll Men //存放結果 iter := collection.Find(nil).Iter() for iter.Next(&result) { fmt.Printf("Result: %v\n", result.NAME) personAll.Persons = append(personAll.Persons, result) } //*******更新資料********** err = collection.Update(bson.M{"name": "ccc"}, bson.M{"$set": bson.M{"name": "ddd"}}) err = collection.Update(bson.M{"name": "ddd"}, bson.M{"$set": bson.M{"phone": "12345678"}}) err = collection.Update(bson.M{"name": "aaa"}, bson.M{"phone": "1245", "name": "bbb"}) //******刪除資料************ _, err = collection.RemoveAll(bson.M{"name": "Ale”})}