golang mongodb Aggregate

来源:互联网 发布:jquery 1.12.4.js下载 编辑:程序博客网 时间:2024/05/25 18:09
q := []bson.M{
        {"$group": bson.M{
            "_id": bson.M{"sessionid":"$sessionid"},
            "sessionid": bson.M{"$first":"$sessionid"},
            "des": bson.M{"$first":"$des"},
            "serial": bson.M{"$first":"$serial"},
            "timestamp": bson.M{"$first":"$timestamp"},
            "timestring": bson.M{"$first":"$timestring"}}},

        {"$sort": bson.M{"timestamp": -1}}}

ss, err := db.AggregatePhonePerf(q)
    if err != nil {
        log.Error(err)
        ret := map[string]interface{}{"code":"006500", "msg": err}
        return c.JSON(500, ret)
    }

//AggregatePhonePerf

func AggregatePhonePerf(pipelineinterface{}) (results []SerialSession, err error) {
    exop := func(c *mgo.Collection)error {
        log.Info(pipeline)
        return c.Pipe(pipeline).All(&results)
    }
    err = getCollection("phonePerf", exop)
    return
}


func getProp(dinterface{}, label string) (interface{}, bool) {
    switch reflect.TypeOf(d).Kind() {
    case reflect.Struct:
        v := reflect.ValueOf(d).FieldByName(label)
        return v.Interface(),true
    case reflect.Map:
        _map, ok := d.(map[string]interface{})
        if ok {
            log.Info(_map, ok)
            v := _map[label]
            if v != nil {
                return v, true
            }
        } else {
            __map, _ok := d.(bson.M)
            log.Info(__map, _ok)
            v := __map[label]
            if v != nil {
                return v, true
            }
        }
    }
    return nil,false
}