Mongodb mongo在聚合中使用temp
我有一些json格式的飞行数据:Mongodb mongo在聚合中使用temp,mongodb,aggregation-framework,Mongodb,Aggregation Framework,我有一些json格式的飞行数据: {"_id":{"$oid":"587d12881603f94800054dc5"},"flight_date":{"$date":"2015-08-23T00:00:00.000Z"},"flight_number":863,"destination_city":" Baltimore, MD","delay_in_minutes":0.0,"cancelled":0.0} 我想做的是找到取消航班率最高的月份。代码I将取消的航班按月分组,并将每个航班除
{"_id":{"$oid":"587d12881603f94800054dc5"},"flight_date":{"$date":"2015-08-23T00:00:00.000Z"},"flight_number":863,"destination_city":" Baltimore, MD","delay_in_minutes":0.0,"cancelled":0.0}
我想做的是找到取消航班率最高的月份。代码I将取消的航班按月分组,并将每个航班除以当年的航班总数。我想做的是将每个月取消的航班除以该月的总航班数(取消和未取消),这样我就得到了合适的比例
var size = db.flights.count();
db.flights.aggregate(
[
{
$project: {
cancelled_flights: { $eq: [ "$cancelled", 1 ] },
month: { $substr: [ "$flight_date", 5, 2 ] },
}
},
{
$match: {"cancelled_flights" : false}
},
{
$group: {
_id : "$month",
total : {$sum : 1 },
}
},
{
$project: {
Total_Cancelled : "$total",
Ratio : { $divide: [ "$total", size] }
}
},
{$sort: {"Ratio":-1}},
{ $limit : 1 }
])
我正在学习mongo,所以请指出我的错误,我会改正的 您可以使用$cond语句获取同一$group中已取消航班和未取消航班的总和
{
$group: {
_id: "$month",
total: { $sum: 1 },
total_canceled: { $sum: { $cond: [{ $eq: ['cancelled_flights', true] }, 1, 0] } }
total_non_canceled: { $sum: { $cond: [{ $eq: ['cancelled_flights', false] }, 1, 0] } }
}
},
$cond语句的工作方式与$cond:[条件,如果为真,如果为假]
因此,在上面,您将有总和“如果匹配条件”,1,如果不匹配,0
然后,您可以使用这些结果进一步处理您选择的信息
组abive将在1$group语句中为您提供标题航班数、取消航班总数和未取消航班总数