golang mgo使用

麦穗儿 · · 641 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

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()

排序 Sort

//按age升序,如果要降序Sort("-age")
iter = c.Find(bson.M{"age": bson.M{"$gte": 33}}).Sort("age").Iter()

限定结果数量 Limit

//使用Limit限定只去5条记录
iter = c.Find(bson.M{"age": bson.M{"$gte": 20}}).Sort("age").Limit(5).Iter()

跳过指定数量的记录 Skip

//跳过两条记录,取接下来的5条记录
iter = c.Find(bson.M{"age": bson.M{"$gte": 20}}).Sort("age").Skip(2).Limit(5).Iter()

计算记录的条数 Count

recordsCount, err := c.Find(bson.M{"age": bson.M{"$gte": 20}}).Count()

选择指定的字段 Select

type User struct {
    Name string
}
var users []User
c.Find(bson.M{"age": bson.M{"$gte": 20}}).Sort("age").Select(bson.M{"name": 1}).All(&users)

以下是自定函数

单条查询

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

代码在
https://github.com/BinWang-sh...


有疑问加站长微信联系(非本文作者)

本文来自:Segmentfault

感谢作者:麦穗儿

查看原文:golang mgo使用

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

641 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传