m := bson.M{
"create_time": bson.M{
"$gte": start,
"$lte": end,
},
"account": account,
"tag": "tag",
}
session.DB("db").C("collect").Find(m).Count()
//这个就可以传入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)
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"})//删除
}