golang mongodb 之 mgo

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

裝完mongodb之後,就是為了學習一下 mgo包的使用
貼一下學習的代碼

package mainimport (    "fmt"    "gopkg.in/mgo.v2"    "gopkg.in/mgo.v2/bson"    "log"    "time")type Person struct {    Name  string    Phone string}/*通過bson:”name”這種方式可以定義MongoDB中集合的欄位名,如果不定義,mgo自動把struct的欄位名首字母小寫作為集合的欄位名。如果不需要獲得id_,Id_可以不定義,在插入的時候會自動產生。*/type User struct {    Id_       bson.ObjectId `bson:"_id"`    Name      string        `bson:"name"`    Age       int           `bson:"age"`    JoinedAt  time.Time     `bson:"joined_at"`    Interests []string      `bson:"interests"`}func main() {    //如果不在本機    //mongodb://myuser:mypass@localhost:40001,otherhost:40001/mydb    session, err := mgo.Dial("localhost:27017")    if err != nil {        panic(err)    }    defer session.Close()    session.SetMode(mgo.Monotonic, true)    /*        其實是分了兩步 1拿db 2拿collection        db := session.DB("test_db")        c := db.C("runoob")    */    c := session.DB("test_db").C("mytable")    //插入資料    err = c.Insert(&Person{"A001", "12312312311"}, &Person{"A002", "123123123002"})    if err != nil {        log.Fatal(err)    }    //查詢    result := Person{}    err = c.Find(bson.M{"name": "A001"}).One(&result)    if err != nil {        log.Fatal(err)    }    fmt.Println("phone = ", result.Phone)    //插入類一種結構文檔    err = c.Insert(&User{        Id_:       bson.NewObjectId(),        Name:      "Jimmy Kuu",        Age:       31,        JoinedAt:  time.Now(),        Interests: []string{"asd", "gdfg"},    })    if err != nil {        panic(err)    }    err = c.Insert(&User{        Id_:       bson.NewObjectId(),        Name:      "Tracy Yu",        Age:       31,        JoinedAt:  time.Now(),        Interests: []string{"Shoping", "TV"},    })    if err != nil {        panic(err)    }    //查詢所有    var users []User    //c.Find(nil).All(&users)    c.Find(bson.M{"age": 31}).All(&users)    for _, item := range users {        fmt.Println(item)    }}

運行後列印

phone =  12312312311{ObjectIdHex("598d3126c3666e1d23000001") Jimmy Kuu 31 2017-08-11 12:23:02.073 +0800 CST [asd gdfg]}{ObjectIdHex("598d3126c3666e1d23000002") Tracy Yu 31 2017-08-11 12:23:02.074 +0800 CST [Shoping TV]}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.