MongoDB聚合分组查询之类型转换
场景:需要将集合某个字段的值进行累加,但该值在集合中的存储类型为字符串,那么进行聚合查询时需要将该字段转换为double或其他类型。
查询语句
统计各个渠道的销售额;原始数据中,销售额用字符串存储,查询时,需先使用$toDouble将字段值转换为double类型,然后再进行分组统计
db.getCollection('order').aggregate([
{
$project:{
'sale':{$toDouble: '$销售额'},
'channel':'$渠道',
'count_date':'$统计日期'
}
},
{
$match:{
"count_date":{$gte:'2020-01-01',$lte:'2020-12-31'}
}
},
{
$group:{
_id: '$channel',
num_tutorial: { $sum: "$sale"}
}
}
])
查询结果
/* 1 */
{
"_id" : "深圳",
"num_tutorial" : 1187294.13
}
/* 2 */
{
"_id" : "广州",
"sales_total" : 41084.94
}
/* 3 */
{
"_id" : "上海",
"sales_total" : 729997.05
}