mongo聚合

分组统计

shell语法

根据等级分组统计

1
> db.users.aggregate([{"$group":{"_id":"bookLevel", "count":{"$sum":1}}}])

根据引导分组统计

1
> db.users.aggregate([{"$group":{"_id":{"guide":"$guide", "guideTwo":"$guideTwo"}, "count":{"$sum":1}}}])

mgo语法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// LevelCount 用户等级分布
type LevelCount struct {
Level int `bson:"_id"`
Count int `bson:"count"`
}
var counts []LevelCount
mongoInstance := db.GetInstance()
defer mongoInstance.Close()
collection := mongoInstance.GetCollection(UsersKey)
m := []bson.M{
{"$group": bson.M{"_id": "$bookLevel", "count": bson.M{"$sum": 1}}},
}
err = collection.Pipe(m).All(&counts)
if err != nil {
return
}