MongoDB中的组合组- Aggregation



我在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

返回这个表

<表类>规AvgMinMaxtbody><<tr>成本2345567453456里程4902353178003
查询
  • 你在一个数据库中有一个集合,你想要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"
}
} ]
)

相关内容

  • 没有找到相关文章

最新更新