以前都mysql,这个新项目用了mongo,便研究下。
本来统计需求其实挺复杂的,但是为了方便做下简化吧:对单价求平均值。入库时存为String类型了,那么做平均计算时需要进行类型转换。聚合函数“$toDouble”进行类型转换写法如下图。
db.yourCollection.aggregate([
{
$group:{
_id:null,
total:{
$sum: {
$toDouble:'$price'
}
}
}
}
])
java写法刚开始时这样写:
Aggregation.newAggregation(Aggregation.group().avg(ConvertOperators.ToDouble.toDouble("price")).as("avgValue"));
直接报错:
Failed to parse number 'price' in $convert with no onError value: Did not consume any digits'
找了好一会都没找到原因,后面才注意方法参数值是Object,而非fieldReference,意思是直接将字符串"price"转成double当然就报错了
研究了下,最终正确写法如下:
Aggregation aggregation = Aggregation.newAggregation(Aggregation.group().avg(ConvertOperators.Convert.convertValueOf("price").to(JsonSchemaObject.Type.doubleType())).as("avgValue"));mongoTemplate.aggregate(Aggregation aggregation, String collectionName, Class<O> outputType);
终于告成!