2015-08-20 80 views
0

我有這樣我run收集的文件不同的數據的數量:MongoDB的:獲取子文件

{ 
    "_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 } } } 
]); 

但我不確定如何達到我想要的預期輸出。

回答

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() 
+0

你是真棒。這真的表明我必須深入閱讀Mongo的文檔。 –