golang 使用mgo 串連MongoDB

來源:互聯網
上載者:User

github:https://github.com/ZhangzheBJUT/blog/blob/master/mgo.md
 
現在MongoDB官方還沒有推出關於官方支援的golang的driver,推薦使用的是mgo.mgo的詳細文檔說明:http://godoc.org/labix.org/v2/mgo 
下面是我開發中自己寫的一個用mgo串連MongoDB資料庫的使用執行個體。

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”})
} 

相關文章

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.