我正在尝试根据计算字段计算MongoDB查询中的百分比 - 不确定这是否可行。我希望能够做的是计算失败百分比:(failed count / total) * 100
以下是一些示例文档:
{
"_id" : ObjectId("52dda5afe4b0a491abb5407f"),
"type" : "build",
"time" : ISODate("2014-01-20T22:39:43.880Z"),
"data" : {
"buildNumber" : 30,
"buildResult" : "SUCCESS"
}
},
{
"_id" : ObjectId("52dd9fede4b0a491abb5407a"),
"type" : "build",
"time" : ISODate("2014-01-20T22:15:07.901Z"),
"data" : {
"buildNumber" : 4,
"buildResult" : "FAILURE"
}
},
{
"_id" : ObjectId("52dda153e4b0a491abb5407b"),
"type" : "build",
"time" : ISODate("2014-01-20T22:21:07.790Z"),
"data" : {
"buildNumber" : 118,
"buildResult" : "SUCCESS"
}
}
这是我正在尝试使用的查询。问题出在FailPercent / $ divide行:
db.col.aggregate([
{ $match: { "data.buildResult" : { $ne : null } } },
{ $group: {
_id: {
month: { $month: "$time" },
day: { $dayOfMonth: "$time" },
year: { $year: "$time" },
},
Aborted: { $sum: { $cond : [{ $eq : ["$data.buildResult", "ABORTED"]}, 1, 0]} },
Failure: { $sum: { $cond : [{ $eq : ["$data.buildResult", "FAILURE"]}, 1, 0]} },
Unstable: { $sum: { $cond : [{ $eq : ["$data.buildResult", "UNSTABLE"]}, 1, 0]} },
Success: { $sum: { $cond : [{ $eq : ["$data.buildResult", "SUCCESS"]}, 1, 0]} },
Total: { $sum: 1 },
FailPercent: { $divide: [ "Failure", "Total" ] }
} },
{ $sort: { "_id.year": 1, "_id.month": 1, "_id.day": 1 } }
])
答案 0 :(得分:23)
你几乎得到了它。只需要进行更改即您必须在额外的FailPercent
阶段计算project
,因为总数仅在group
阶段完成后才可用。试试这个:
db.foo.aggregate([
{ $match: { "data.buildResult" : { $ne : null } } },
{ $group: {
_id: {
month: { $month: "$time" },
day: { $dayOfMonth: "$time" },
year: { $year: "$time" },
},
Aborted: { $sum: { $cond : [{ $eq : ["$data.buildResult", "ABORTED"]}, 1, 0]} },
Failure: { $sum: { $cond : [{ $eq : ["$data.buildResult", "FAILURE"]}, 1, 0]} },
Unstable: { $sum: { $cond : [{ $eq : ["$data.buildResult", "UNSTABLE"]}, 1, 0]} },
Success: { $sum: { $cond : [{ $eq : ["$data.buildResult", "SUCCESS"]}, 1, 0]} },
Total: { $sum: 1 }
} },
{$project:{Aborted:1, Failure:1, Unstable:1, Success:1, Total:1, FailPercent: { $divide: [ "$Failure", "$Total" ]}}},
{ $sort: { "_id.year": 1, "_id.month": 1, "_id.day": 1 } }
])