$ push和$ sum与子文档上的聚合框架

时间:2015-08-26 01:44:30

标签: mongodb mongoose mongodb-query aggregation-framework

我的数据如下:

<xsl:value-of select="
    format-number(xs:integer(number($input) * 10000) div 10000, '#.0000')" /> 

我试图得到这样的结果:

{
    "_id" : ObjectId("55d4410544c96d6f6578f893"),
    "executionProject" : "Project1",
    "suiteList" : [ 
        {
            "suiteName": "Suite1",
            "suiteStatus" : "PASS",
        },
        {
            "suiteName": "Suite2",
            "suiteStatus" : "FAIL",
        },
        {
            "suiteName": "Suite3",
            "suiteStatus" : "PASS",
        }
    ],
    "runEndTime" : ISODate("2015-08-19T08:40:47.049Z")
}

{
    "_id" : ObjectId("55d4410544c96d6f6578f894"),
    "executionProject" : "Project1",
    "suiteList" : [ 
        {
            "suiteName": "Suite1",
            "suiteStatus" : "PASS",
        },
        {
            "suiteName": "Suite2",
            "suiteStatus" : "FAIL",
        },
        {
            "suiteName": "Suite3",
            "suiteStatus" : "FAIL",
        }
    ],
    "runEndTime" : ISODate("2015-08-19T08:50:47.049Z")
}

此处我尝试按{ "executionProject": "Project1", "data": [ { "date": "2015-08-19 08:40:47", "suitePass": 2, "suiteFail": 1 }, { "date": "2015-08-19 08:50:47", "suitePass": 1, "suiteFail": 2 } ] } 进行分组,并将executionProject以及runEndTime的通过和失败计数推送到结果。

我尝试了这个,但给了我错误的投射方式:

suites

1 个答案:

答案 0 :(得分:1)

首先,您需要按文档分组才能获得套件总数,然后在项目分组时添加到数组中。也不要忘记&#34;排序&#34;如果你想按顺序排列:

set HOUR=%HOUR: =0%

产地:

  [
      { "$unwind": "$suiteList" },
      { "$group": {
        "_id": "$_id",
        "executionProject": { "$first": "$executionProject" },
        "suite-pass": { 
          "$sum": {
            "$cond": [
              { "$eq": [ "$suiteList.suiteStatus", "PASS" ] },
              1,
              0
            ]
          }
        },
        "suite-fail": { 
          "$sum": {
            "$cond": [
              { "$eq": [ "$suiteList.suiteStatus", "FAIL" ] },
              1,
              0
            ]
          }
        },
        "date": { "$first": "$runEndTime" }
      }},
      { "$sort": { "executionProject": 1, "date": 1 } },
      { "$group": {
        "_id": "$executionProject",
        "data": {
          "$push": { 
            "suite-pass": "$suite-pass",
            "suite-fail": "$suite-fail",
            "date": "$date"
          }
        }
      }}
  ]