Golang使用mgo.v2包操作MongoDB的基础示例

go get -u gopkg.in/mgo.v2

 

package main
 
import (
    "log"
    "time"
 
    "gopkg.in/mgo.v2"
    "gopkg.in/mgo.v2/bson"
)
 
const (
    MongoDBHosts = "127.0.0.1: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"})
————————————————
版权声明:本文为CSDN博主「名字长点才好记」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/bianlitongcn/article/details/108535228

posted @ 2021-08-19 17:27  码农骆驼  阅读(759)  评论(1编辑  收藏  举报