我试图在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 } }
])
错误元素是我试图将两者加在一起的那个 - 我已经尝试了其他几种语法选项而没有太大的成功。谢谢。
答案 0 :(得分: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 } }
])
答案 1 :(得分:1)
您可以使用管道中的$ project阶段来执行此操作,例如:
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}}
])
答案 2 :(得分: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 } }
])