golang操作mongodb

所需包engine

import (
    "fmt"
    "sync"
    "engine/mgo"
    "engine/mgo/bson"
)

var (
    session *mgo.Session
    db      *mgo.Database
    c       *mgo.Collection
    mux     sync.Mutex
)

func init() {
    mux.Lock()
    defer mux.Unlock()

    if session != nil {
        return
    }

    // new session
    session, err := mgo.Dial("192.168.0.229:27017")
    checkErr("dial fail", err)

    session.SetMode(mgo.Monotonic, true)

    // new db
    if db != nil {
        return
    }
    db = session.DB("Test")

    // new collection
    if c != nil {
        return
    }
    c = db.C("person")
}

func checkErr(data string, err error) {
    if err != nil {
        fmt.Println(data + ": " + err.Error())
    }
}

type Person struct {
    Name  string
    Email string
}

func New() *Person {
    return &Person{
        Name:  "zhangbaolang",
        Email: "zhagnbaoliang.vip@gmail.com",
    }
}

func main() {

    // insert
    err := c.Insert(New())
    checkErr("insert fail", err)

    // find
    m := bson.M{"name": "zhangbaolang"}

    query := c.Find(m)

    // one
    person := Person{}
    err = query.One(&person)
    //fmt.Println(person.Name)
    checkErr("query fail", err)

    fmt.Println(person.Email)

    if session != nil {
        session.Close()
    }
}
阅读更多
文章标签: golang mongodb
上一篇golang strings包
下一篇Redis Client for .net组件
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭