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)

    }

点赞(1474)

评论列表共有 0 条评论

立即
投稿
返回
顶部