教程集 www.jiaochengji.com
教程集 >  Golang编程  >  golang教程  >  正文 golang mgo使用

golang mgo使用

发布时间:2021-05-23   编辑:jiaochengji.com
教程集为您提供golang mgo使用等资源,欢迎您收藏本站,我们将为您提供最新的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()

排序 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...

到此这篇关于“golang mgo使用”的文章就介绍到这了,更多文章或继续浏览下面的相关文章,希望大家以后多多支持JQ教程网!

您可能感兴趣的文章:
go mod使用
golang mgo使用
golang 扩展package 列表
arcgis datastore服务不可用_Golang 微服务教程(三)
golang基础教程
Golang:国内 go get 无法下载的问题
Golang 中 RSA 算法的使用
Jetbrains(phpstorm, golang..)系列产品重置试用方法
Golang-使用goconfig 读取配置文件
PHP7 Swoole/Nginx/Golang 数字货币交易所通信方式

[关闭]
~ ~