##### 最近在使用golang做数据统计,需要从mongodb中读取数据,在聚合这块遇到问题
#### 1、使用的三方库
`"gopkg.in/mgo.v2" `
```go
import (
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
```
#### 2、mongodb中存储的数据格式
```json
{ "_id" : ObjectId("5a605bc0ec555c45052da98c"), "event" : "userRecord", "data" : { "time" : "2018-01-18 16:31:46", "remainNum" : 13410500, "num" : 3000, "itemID" : 1001, "type" : 1, "sysID" : 15, "uid" : "4189034" }, "__v" : 0 }
{ "_id" : ObjectId("5a605bc0da43564502aae81d"), "event" : "userRecord", "data" : { "time" : "2018-01-18 16:31:46", "remainNum" : 1030, "num" : 50, "itemID" : 3001, "type" : 1, "sysID" : 15, "uid" : "4189034" }, "__v" : 0 }
```
#### 3、定义bson,通过Pipe查询
```go
func main() {
session, err := mgo.Dial("192.168.12.211:27017")
if err != nil {
fmt.Println(err)
}
session.SetMode(mgo.Monotonic, true)
db := session.DB("storeServer")
c := db.C("userrecords")
o1 := bson.M{"$match": bson.M{"data.uid": bson.M{"$gt": "30000"}}}
o2 := bson.M{"$match": bson.M{"data.time": bson.M{"$lte": time.Now().Format("2006-01-02 15:04:05")}}}
o3 := bson.M{"$match": bson.M{"data.time": bson.M{"$gt": time.Now().Add(time.Minute * -10).Format("2006-01-02 15:04:05")}}}
o4 := bson.M{"$group": bson.M{"_id": "$data.itemID", "num": bson.M{"$sum": "$data.num"}}}
//o4只能使用_id,作为聚合键,使用别的字段就报错(例如sysID,itemID),例如o5中使用event
//o5 := bson.M{"$group": bson.M{"event": "$data.type", "num": bson.M{"$sum": "$data.num"}}}
//使用别的字段,报错:
//ERROR : exception: the group aggregate field 'event' must be defined as an expression inside an object
operations := []bson.M{o1, o2, o3, o4}
pipe := c.Pipe(operations)
results := []bson.M{}
err = pipe.All(&results)
if err != nil {
fmt.Printf("ERROR : %s\n", err.Error())
return
}
fmt.Printf("%+v\n", results) //[map[_id:3001 num:50] map[_id:1001 num:3000]]
}
```
#### 4、问题
通过报错,可以看出,group聚合字段,必须定义为对象内的表达式。我尝试了定义在内部别的字段,都报错,bson是不是不支持内部嵌套的对象,希望大佬们帮组下
有疑问加站长微信联系(非本文作者)