2014-03-05 76 views
0

我想在MongoDB中總結兩個聚合列。MongoDB添加兩個聚合列

這裏是一個示例文件:

{ 
    "_id" : ObjectId("52de8f56e4b0a491abb540e2"), 
    "type" : "build", 
    "time" : ISODate("2014-01-21T15:16:38.384Z"), 
    "data": { 
     "unitTests": { 
      "testType": "TestNG", 
      "totalTests": 6153, 
      "failedTests": 2, 
      "skippedTests": 1 
     } 
    } 
} 

我想補充failedTests和skippedTests在一起。下面是該查詢我到目前爲止:

db.builds.aggregate([  
    { $match: { "data.unitTests.testType" : { $ne : null} }}, 
    { $group: {   
     _id: {    
      month: { $month: "$time" },    
      day: { $dayOfMonth: "$time" },    
      year: { $year: "$time" },      
     }, 
     total: { $avg: "$data.unitTests.totalTests" }, 
     failed: { $avg: "$data.unitTests.failedTests" }, 
     skipped: { $avg: "$data.unitTests.skippedTests" }, 
     error: { $add: ["$data.unitTests.failedTests", "$data.unitTests.skippedTests"] }, 
    } },  
    { $sort: { "_id.year": 1, "_id.month": 1, "_id.day": 1 } } 
]) 

錯誤元素是一個地方我想補充兩個在一起 - 我已經嘗試了其他幾個語法選項但沒有成功。謝謝。

回答

1

你應該使用$add$project,不與$group

db.builds.aggregate([  
{ $match: { "data.unitTests.testType" : { $ne : null} }}, 
{ $group: {   
    _id: {    
     month: { $month: "$time" },    
     day: { $dayOfMonth: "$time" },    
     year: { $year: "$time" },      
    }, 
    total: { $avg: "$data.unitTests.totalTests" }, 
    failed: { $avg: "$data.unitTests.failedTests" }, 
    skipped: { $avg: "$data.unitTests.skippedTests" } 

} }, 
{ $project: { 
    total: 1, 
    failed: 1, 
    skipped: 1, 
    error: { $add: ["$failed", "$skipped"] } 
} }, 
{ $sort: { "_id.year": 1, "_id.month": 1, "_id.day": 1 } } 
]) 
0

嘗試第二group

db.builds.aggregate([  
    { $match: { "data.unitTests.testType" : { $ne : null} }}, 
    { $group: {   
     _id: {    
      month: { $month: "$time" },    
      day: { $dayOfMonth: "$time" },    
      year: { $year: "$time" },      
     }, 
     total: { $avg: "$data.unitTests.totalTests" }, 
     failed: { $avg: "$data.unitTests.failedTests" }, 
     skipped: { $avg: "$data.unitTests.skippedTests" } 
    } }, 
    { $group: { _id: '$_id', total: '$total', failed: '$failed', skipped: '$skipped', error: { $add: ['$failed', '$skipped'] } },  
    { $sort: { "_id.year": 1, "_id.month": 1, "_id.day": 1 } } 
]) 
+0

謝謝,但它拋出一個錯誤:「ERRMSG」:「異常:該組總場的‘合計’絕被定義爲一個對象內的表達式「, – JamesE

1

您可以在管道就像使用$項目階段做到這一點:

db.builds.aggregate([  
{$match: {"data.unitTests.testType": {$ne: null}}}, 
{$group: {_id: {month: {$month: "$time"},day: {$dayOfMonth: "$time"},year: {$year: "$time"}}, 
     total: {$avg: "$data.unitTests.totalTests"}, 
     failed: {$avg: "$data.unitTests.failedTests"}, 
     skipped: {$avg: "$data.unitTests.skippedTests"}} 
}, 
{$project: {total: 1, 
     failed: 1, 
     skipped: 1, 
     error: {$add: ["$failed","$skipped"]}} 
}, 
{$sort: {"_id.year": 1,"_id.month": 1,"_id.day": 1}} 
])