我的run
集合中有这样的文档:
{
"_id" : ObjectId("55d4410544c96d6f6578f893"),
"runName" : "1439973637614",
"suiteList": [
{
"suiteStatus": "PASS"
},
{
"suiteStatus": "PASS"
}
]
}
{
"_id" : ObjectId("55d44eb4c0422e7b8bffe76b"),
"runName" : "1439977140396",
"suiteList": [
{
"suiteStatus": "FAIL"
},
{
"suiteStatus": "PASS"
}
]
}
{
"_id" : ObjectId("55d44f0bc0422e7b8bffe76f"),
"runName" : "1439977227370",
"suiteList": [
{
"suiteStatus": "FAIL"
},
{
"suiteStatus": "FAIL"
}
]
}
现在我想得到如下输出:
{
"runName" : "1439973637614",
{
"pass": 2,
"fail": 0
}
}
{
"runName" : "1439977140396",
{
"pass": 1,
"fail": 1
}
}
{
"runName" : "1439977227370",
{
"pass": 0,
"fail": 2
}
}
我知道如何使用以下方法获取suiteList中所有级别的传递和失败计数列表:
db.testruns.aggregate([
{ $unwind: "$suiteList" },
{ $group: { _id: "$suiteList.suiteStatus", count: { $sum: 1 } } }
]);
但我不确定如何达到我想要的预期输出。
答案 0 :(得分:3)
您的聚合查询需要进行一些修改,您应该在组中使用$cond,这样聚合如下:
db.testruns.aggregate({
"$unwind": "$suiteList"
}, {
"$group": {
"_id": "$runName",
"pass": {
"$sum": {
"$cond": {
"if": {
"$eq": ["$suiteList.suiteStatus", "PASS"]
},
"then": 1,
"else": 0
}
}
},
"fail": {
"$sum": {
"$cond": {
"if": {
"$eq": ["$suiteList.suiteStatus", "FAIL"]
},
"then": 1,
"else": 0
}
}
}
}
}).pretty()