mongodb BSON的基本使用教程


1.查找 Find

這里查找時間戳內,賬號為account,標簽為tag的數據並統計個數。
m := bson.M{
    "create_time": bson.M{
      "$gte": start,
      "$lte": end,
    },
    "account": account,
    "tag": "tag",
  }
  session.DB("db").C("collect").Find(m).Count()

2.聚合管道在mgo中為Pipe(pipeline interface{})

這個和bash中使用的管道很像,數據可以被層層處理。一般傳入的參數為[]bson.M。這個[]bson.M里如果還有嵌套則還要使用[]bson.M
- 比如這里首先匹配標簽和賬號
- 時間戳在一段時間內
- 然后根據名字分組統計數量
- 最后排序取最前面的三個。
這個就可以傳入Pipe
  m := []bson.M{
    {"$match": bson.M{"tag": "tag", "account": account, "create_time": bson.M{"$gte": start, "$lte": end}}},
    {"$group": bson.M{"_id": "$TagName", "count": bson.M{"$sum": 1}}},
    {"$sort": bson.M{"count": -1}},
    {"$limit": 3},
  }
  //這里就可以取到輸出的數據
  var values []result
  session.DB("db").C("collect").Pipe(m).All(&values)

簡單介紹1

package main
import (
 "gopkg.in/mgo.v2"
 "log"
 "gopkg.in/mgo.v2/bson"
)
type User struct {
 Id    bson.ObjectId `bson:"_id"`
 Name   string    `bson:"name"`
 PassWord string    `bson:"pass_word"`
 Age   int      `bson:"age"`
}
func main() {
 db, err := mgo.Dial("mongodb://192.168.2.28:27017,192.168.2.28:27018,192.168.2.28:27019/?replicaSet=howie")
 if err != nil {
 log.Fatalln(err)
 }
 defer db.Close()
 db.SetMode(mgo.Monotonic, true)
 c := db.DB("howie").C("person")
 //插入
 /*c.Insert(&User{
 Id:    bson.NewObjectId(),
 Name:   "JK_CHENG",
 PassWord: "123132",
 Age: 2,
 }, &User{
 Id:    bson.NewObjectId(),
 Name:   "JK_WEI",
 PassWord: "qwer",
 Age: 5,
 }, &User{
 Id:    bson.NewObjectId(),
 Name:   "JK_HE",
 PassWord: "6666",
 Age: 7,
 })*/
 var users []User
 c.Find(nil).All(&users) //查詢全部數據
 log.Println(users)
 c.FindId(users[0].Id).All(&users) //通過ID查詢
 log.Println(users)
 c.Find(bson.M{"name": "JK_WEI"}).All(&users) //單條件查詢(=)
 log.Println(users)
 c.Find(bson.M{"name": bson.M{"$ne": "JK_WEI"}}).All(&users) //單條件查詢(!=)
 log.Println(users)
 c.Find(bson.M{"age": bson.M{"$gt": 5}}).All(&users) //單條件查詢(>)
 log.Println(users)
 c.Find(bson.M{"age": bson.M{"$gte": 5}}).All(&users) //單條件查詢(>=)
 log.Println(users)
 c.Find(bson.M{"age": bson.M{"$lt": 5}}).All(&users) //單條件查詢(<)
 log.Println(users)
 c.Find(bson.M{"age": bson.M{"$lte": 5}}).All(&users) //單條件查詢(<=)
 log.Println(users)
 /*c.Find(bson.M{"name": bson.M{"$in": []string{"JK_WEI", "JK_HE"}}}).All(&users) //單條件查詢(in)
 log.Println(users)
 c.Find(bson.M{"$or": []bson.M{bson.M{"name": "JK_WEI"}, bson.M{"age": 7}}}).All(&users) //多條件查詢(or)
 log.Println(users)
 c.Update(bson.M{"_id": users[0].Id}, bson.M{"$set": bson.M{"name": "JK_HOWIE", "age": 61}}) //修改字段的值($set)
 c.FindId(users[0].Id).All(&users)
 log.Println(users)
 c.Find(bson.M{"name": "JK_CHENG", "age": 66}).All(&users) //多條件查詢(and)
 log.Println(users)
 c.Update(bson.M{"_id": users[0].Id}, bson.M{"$inc": bson.M{"age": -6,}}) //字段增加值($inc)
 c.FindId(users[0].Id).All(&users)
 log.Println(users)*/
 //c.Update(bson.M{"_id": users[0].Id}, bson.M{"$push": bson.M{"interests": "PHP"}}) //從數組中增加一個元素($push)
 c.Update(bson.M{"_id": users[0].Id}, bson.M{"$pull": bson.M{"interests": "PHP"}}) //從數組中刪除一個元素($pull)
 c.FindId(users[0].Id).All(&users)
 log.Println(users)
 c.Remove(bson.M{"name": "JK_CHENG"})//刪除
}

簡單介紹2

以下所有例子中結構定義如下:
type User struct {
    Id_ bson.ObjectId `bson:"_id"`
    Name string `bson:"name"`
    Age int `bson:"age"`
    JoinedAt time.Time `bson:"joined_at"`
    Interests []string `bson:"interests"
}
1、查詢
通過func (c *Collection) Find(query interface{}) *Query來進行查詢,返回的Query struct可以有附加各種條件來進行過濾。

通過Query.All()可以獲得所有結果,通過Query.One()可以獲得一個結果,注意如果沒有數據或者數量超過一個,One()會報錯。

條件用bson.M{key: value},注意key必須用MongoDB中的字段名,而不是struct的字段名。
1.1、查詢所有
var users []User
c.Find(nil).All(&users)
上面代碼可以把所有Users都查出來:

1.2、根據ObjectId查詢
id := "5204af979955496907000001"
objectId := bson.ObjectIdHex(id)
user := new(User)
c.Find(bson.M{"_id": objectId}).One(&user)
更簡單的方式是直接用FindId()方法:
c.FindId(objectId).One(&user)

1.3、單條件查詢
=($eq)
c.Find(bson.M{"name": "Jimmy Kuu"}).All(&users)

!=($ne)
c.Find(bson.M{"name": bson.M{"$ne": "Jimmy Kuu"}}).All(&users)

>($gt)
c.Find(bson.M{"age": bson.M{"$gt": 32}}).All(&users)

<($lt)
c.Find(bson.M{"age": bson.M{"$lt": 32}}).All(&users)

>=($gte)
c.Find(bson.M{"age": bson.M{"$gte": 33}}).All(&users)

<=($lte)
c.Find(bson.M{"age": bson.M{"$lte": 31}}).All(&users)

in($in)
c.Find(bson.M{"name": bson.M{"$in": []string{"Jimmy Kuu", "Tracy Yu"}}}).All(&users)
no in($nin)
同$in,

是否包含這個鍵($exists)
c.Find(bson.M{"name": bson.M{"$exists": true}}).All(&users)

查詢鍵值為null的字段
c.Find(bson.M{"name": bson.M{"$in":[]interface{}{null}, "$exists": true}}).All(&users)

模糊查詢($regex)
c.Find(bson.M{"name": bson.M{"$regex": "^[0-9]+"}}).All(&users)

$size
查詢鍵值為長度是size的數組
c.Find(bson.M{"Interests": bson.M{"$size": 3}}).All(&users)
上面就是查詢Interests數組長度為3的所有人

$all
查詢數組中包含所有值得匹配(不分順序,只看包含與否)
c.Find(bson.M{"Interests": bson.M{"$all": []string{"11","22","33"}}}).All(&users)
上面就是查詢Interests中包含11,22,33的所有人

key.index
如果要查詢數組指定位置
c.Find(bson.M{"Interests.2": "33"}).All(&users)
以上就是查詢Interests的第二個元素為"33"的所有人

1.4、多條件查詢
and($and)
c.Find(bson.M{"name": "Jimmy Kuu", "age": 33}).All(&users)

or($or)
c.Find(bson.M{"$or": []bson.M{bson.M{"name": "Jimmy Kuu"}, bson.M{"age": 31}}}).All(&users)

1.5 and 和or 同時使用
(from_account==‘123’ or to_account=‘123’) and(timestamp < '查詢時間')
weher1:=bson.M{"$or":[]bson.M{bson.M{"from_account": 123}, bson.M{"to_account": 123}}}
weher2:=bson.M{"timestamp":bson.M{"$lt":'查詢時間'}}
where_contanct :=bson.M{"$and":[]bson.M{weher1,weher2}}
c.Find(where_contanct ).All(&users)

2、修改
通過func (*Collection) Update來進行修改操作。
func (c *Collection) Update(selector interface{}, change interface{}) error
注意修改單個或多個字段需要通過$set操作符號,否則集合會被替換。
2.1、($set)
修改字段的值
c.Update(
bson.M{"_id": bson.ObjectIdHex("5204af979955496907000001")},
bson.M{"$set": bson.M{ "name": "Jimmy Gu", "age": 34, }}
)
2.2、inc($inc)
字段增加值
c.Update(
bson.M{"_id": bson.ObjectIdHex("5204af979955496907000001")},
bson.M{"$inc": bson.M{ "age": -1, }}
)
2.3、push($push)
從數組中增加一個元素
c.Update(
bson.M{"_id": bson.ObjectIdHex("5204af979955496907000001")},
bson.M{"$push": bson.M{ "interests": "Golang", }}
)
2.4、pull($pull)
從數組中刪除一個元素
c.Update(
bson.M{"_id": bson.ObjectIdHex("5204af979955496907000001")},
bson.M{"$pull": bson.M{ "interests": "Golang", }}
)
2.5、刪除
c.Remove(bson.M{"name": "Jimmy Kuu"})

3.對數據進行排序  使用Sort函數
func (q *Query) Sort(fields ...string) *Query
 var users []User
    // 按照age字段降序排列,如果升序去掉橫線"-"就可以了
    err := c.Find(nil).Sort("-age").All(&users)
    if err != nil {
        panic(err)
    }

4.分頁查詢
使用Skip函數和Limit函數
func (q *Query) Skip(n int) *Query
func (q *Query) Limit(n int) *Query

var users []User
    // 表示從偏移位置為2的地方開始取兩條記錄
    err := c.Find(nil).Sort("-age").Skip(2).Limit(2).All(&users)
    if err != nil {
        panic(err)
    }

 

實際使用

    m := bson.M{}
    m["platform"] = platform
    m["cdate"] = bson.M{"$gte": begindate, "$lte": enddate}
    for k,v := range param {
        if v != "all" {
            m[k] = v
        }
    }
    paramBson := []bson.M{
        {"$match":m},
        {"$group": bson.M{"_id": "$create_date", "pv": bson.M{"$sum": "$pv"}, "uv": bson.M{"$sum": "$uv"}, "costs": bson.M{"$sum": "$costs"}}},
        {"$sort": bson.M{"_id":1}},
    }
    c.Pipe(paramBson).All(&m)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM