聚合统计平均高度
client := global.GvaMongo.Database(global.GvaConfig.MongoDB.Dbname).Collection(global.Collection)
groupStage :=bson.D{
{"$group", bson.D{
{"_id", bson.D{
{"lei_xing", "$lei_xing"},
{"xing_hao", "$xing_hao"},
{"pi_hao", "$pi_hao"},
},
},
{"avg_gao_du", bson.D{
//将其他类型的高度转换为double类型,为null的话就设置为0
{"$avg",bson.D{{"$convert",bson.D{{"input","$gao_du"},{"to","double"},{"onError","高度数据有误"},{"onNull",0}}}}},
},
},
},
},
}
//var matchCondition = []bson.E{}
var matchCondition = bson.M{}
matchStage :=bson.D{{"$match",matchCondition}}
cur,_:= client.Aggregate(context.TODO(),mongo.Pipeline{matchStage,groupStage})
// Get a list of all returned documents and print them out. // See the mongo.Cursor documentation for more examples of using cursors.
var results []map[string]interface{}
if err = cur.All(context.TODO(), &results);
err != nil { log.Fatal(err) }
运行结果: