golang mgo使用

golang对MongoDB的操作使用gopkg.in/mgo.v2库操作。如下是基本的一些用法

连接

package main

import (
    "log"
    "time"

    "gopkg.in/mgo.v2"
)

const (
    MongoDBHosts = "172.17.84.205:27017"
    AuthDatabase = "test"
    AuthUserName = "test"
    AuthPassword = "123456"
    MaxCon       = 300
)

func main() {
    mongoDBDialInfo := &mgo.DialInfo{
        Addrs:    []string{MongoDBHosts},
        Timeout:  60 * time.Second,
        Database: AuthDatabase,
        Username: AuthUserName,
        Password: AuthPassword,
    }

    session, err := mgo.DialWithInfo(mongoDBDialInfo)
    if err != nil {
        log.Fatalf("CreateSession failed:%\n", err)
    }

    //设置连接池的大小
    session.SetPoolLimit(MaxCon)
    defer session.Close()
}

插入

package main

import (
    "log"
    "time"

    "gopkg.in/mgo.v2"
    "gopkg.in/mgo.v2/bson"
)

const (
    MongoDBHosts = "172.17.84.205:27017"
    AuthDatabase = "test"
    AuthUserName = "test"
    AuthPassword = "123456"
    MaxPoolSize  = 300
)

type Person struct {
    Name      string
    Phone     string
    City      string
    Age       int8
    IsMan     bool
    Interests []string
}

func main() {
    mongoDBDialInfo := &mgo.DialInfo{
        Addrs:    []string{MongoDBHosts},
        Timeout:  60 * time.Second,
        Database: AuthDatabase,
        Username: AuthUserName,
        Password: AuthPassword,
    }

    session, err := mgo.DialWithInfo(mongoDBDialInfo)
    if err != nil {
        log.Fatalf("CreateSession failed:%\n", err)
    }

    session.SetPoolLimit(MaxPoolSize)
    defer session.Close()

    session.SetMode(mgo.Monotonic, true)

    err = createData(session, "test", "people")
    if err != nil {
        log.Fatal(err)
    }
}

func createData(session *mgo.Session, dbname string, tablename string) error {

    persons := []Person{
        Person{Name: "Tony", Phone: "123432", City: "Shanghai", Age: 33, IsMan: true, Interests: []string{"music", "tea", "collection"}},
        Person{Name: "Mary", Phone: "232562", City: "Beijing", Age: 43, IsMan: false, Interests: []string{"sport", "film"}},
        Person{Name: "Tom", Phone: "123432", City: "Suzhou", Age: 22, IsMan: true, Interests: []string{"music", "reading"}},
        Person{Name: "Bob", Phone: "123432", City: "Hangzhou", Age: 32, IsMan: true, Interests: []string{"shopping", "coffee"}},
        Person{Name: "Alex", Phone: "15772", City: "Shanghai", Age: 21, IsMan: true, Interests: []string{"music", "chocolate"}},
        Person{Name: "Alice", Phone: "43456", City: "Shanghai", Age: 42, IsMan: false, Interests: []string{"outing", "tea"}},
        Person{Name: "Ingrid", Phone: "123432", City: "Shanghai", Age: 22, IsMan: false, Interests: []string{"travel", "tea"}},
        Person{Name: "Adle", Phone: "123432", City: "Shanghai", Age: 20, IsMan: false, Interests: []string{"game", "coffee", "sport"}},
        Person{Name: "Smith", Phone: "54223", City: "Fuzhou", Age: 54, IsMan: true, Interests: []string{"music", "reading"}},
        Person{Name: "Bruce", Phone: "123432", City: "Shanghai", Age: 31, IsMan: true, Interests: []string{"film", "tea", "game", "shoping", "reading"}},
    }

    cloneSession := session.Clone()
    c := cloneSession.DB(dbname).C(tablename)

    for _, item := range persons {
        err := c.Insert(&item)
        if err != nil {
            panic(err)
        }
    }

    return nil
}

查询

条件符号

$ne相当与"!"

//$ne city != Shanghai
iter := c.Find(bson.M{"city": bson.M{"$ne": "Shanghai"}}).Iter()

$gt相当于">"

iter = c.Find(bson.M{"age": bson.M{"$gt": 31}}).Iter()

$lt相当与"<"

iter = c.Find(bson.M{"age": bson.M{"$lt": 35}}).Iter()

$gte相当于">="

iter = c.Find(bson.M{"age": bson.M{"$gte": 33}}).Iter()

$lte相当于"<="

iter = c.Find(bson.M{"age": bson.M{"$lte": 33}}).Iter()

$in在集合内

iter = c.Find(bson.M{"city": bson.M{"$in": []string{"Shanghai", "Hangzhou"}}}).Iter()

$nin不在集合内

iter = c.Find(bson.M{"city": bson.M{"$nin": []string{"Shanghai", "Hangzhou"}}}).Iter()

$exists是否包含键(city键存在的所有记录)

iter = c.Find(bson.M{"city": bson.M{"$exists": true}}).Iter()

键值为null(键存在,键值为null)

iter = c.Find(bson.M{"city": bson.M{"$in": []interface{}{nil}, "$exists": true}}).Iter()

$size 键值长度为指定值的数组

iter = c.Find(bson.M{"interests": bson.M{"$size": 3}}).Iter()

$all 包含所有值的匹配

iter = c.Find(bson.M{"interests": bson.M{"$all": []string{"music", "reading"}}}).Iter()

key.index查询数组指定位置的值(例如第一兴趣 interests.0)

iter = c.Find(bson.M{"interests.0": "music"}).Iter()

多条件查询

条件与

iter = c.Find(bson.M{"city": "Shanghai", "age": bson.M{"$gte": 33}}).Iter()

条件或($or)

iter = c.Find(bson.M{"$or": []bson.M{bson.M{"city": "Hangzhou"}, bson.M{"phone": "123432"}}}).Iter()

以下是自定函数

单条查询

func QueryOne(session *mgo.Session, dbname string, tablename string, query interface{}, result interface{}) error {
    copySession := session.Clone()
    defer copySession.Close()

    collection := copySession.DB(dbname).C(tablename)
    err := collection.Find(query).One(result)

    if err != nil {
        log.Fatal(err)
        return err
    }

    return nil
}

调用

result := Person{}
err = QueryOne(session, "test", "people", &bson.M{"name": "Ale"}, &result)
log.Println("Phone:", result.Phone)

根据ObjectId查询

id := "5dca1bb523c7a64c24e53ea7"
    objectId := bson.ObjectIdHex(id)
    err = QueryOne(session, "test", "people", &bson.M{"_id": objectId}, &result)
    log.Println(result)

多条查询

func QueryAll(session *mgo.Session, dbname string, tablename string, query interface{}) *mgo.Iter {
    copySession := session.Clone()
    defer copySession.Close()

    collection := copySession.DB(dbname).C(tablename)

    //Using iterator prevent from taking up too much memory
    iter := collection.Find(query).Iter()

    if iter != nil {
        return iter
    }

    return nil
}

调用

iter := QueryAll(session, "test", "people", bson.M{"city": bson.M{"$ne": "Shanghai"}})

for iter.Next(&result) {
    log.Println(result)
}

修改

func (c *Collection) Update(selector interface{}, change interface{}) error

$set修改字段的值。如果没有该字段通过$set后会添加响应的字段

c.Update(bson.M{"name": "Tony"}, bson.M{"$set": bson.M{"name": "Tony Tang", "age": 30}})

$inc增加字段的值

//Tony Tang's age + 1
c.Update(bson.M{"name": "Tony Tang"}, bson.M{"$inc": bson.M{"age": 1}})

$push数组元素增加一个

c.Update(bson.M{"name": "Tony Tang"}, bson.M{"$push": bson.M{"interests": "dream"}})

$pull数组中元素减少一个

c.Update(bson.M{"name": "Tony Tang"}, bson.M{"$pull": bson.M{"interests": "dream"}})

删除

c.Remove(bson.M{"name": "Smith"})
我来评几句
登录后评论

已发表评论数()

相关站点

热门文章