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"})//刪除
}