我在MySQL
中有此代码对应于一个简单的汽车数据库
SELECT
"Cost" AS "Metric",
AVG(car_cost) As "Avg",
MIN(car_cost) As "Min",
MAX(car_cost) As "Max",
"Dollars" As "Unit"
from db.car_data
union SELECT
'Mileage',
AVG(car_mileage),
MIN(car_mileage),
MAX(car_mileage),
'Miles'
from db.car_data
返回这个表
<表类>规 Avg Min Max tbody><<tr>成本 2345 5674 53456 里程49023 53 178003 表类>
查询
- 你在一个数据库中有一个集合,你想要6个累加器
- 您可以将它们分成3组,甚至在2个文档中,以获得确切的SQL类结果
*我们有$facet
$unionWith
等,但你不需要这些,不需要做多个聚合,只有一个你可以得到所有你需要的
此处测试代码
aggregate(
[ {
"$group" : {
"_id" : null,
"avg_cost" : {
"$avg" : "$car_cost"
},
"min_cost" : {
"$min" : "$car_cost"
},
"max_cost" : {
"$max" : "$car_cost"
},
"avg_mileage" : {
"$avg" : "$car_mileage"
},
"min_mileage" : {
"$min" : "$car_mileage"
},
"max_mileage" : {
"$max" : "$car_mileage"
}
}
}, {
"$set" : {
"array" : [ {
"metric" : "cost",
"avg" : "$avg_cost",
"min" : "$min_cost",
"max" : "$max_cost"
}, {
"metric" : "mileage",
"avg" : "$avg_mileage",
"min" : "$min_mileage",
"max" : "$max_mileage"
} ]
}
}, {
"$unwind" : {
"path" : "$array"
}
}, {
"$replaceRoot" : {
"newRoot" : "$array"
}
} ]
)