我在 MongoDB 中有这个集合:
[
{ _id: "...", "project": 244, "scanner": "sonarqube", "version": 1 },
{ _id: "...", "project": 244, "scanner": "sonarqube", "version": 2 },
{ _id: "...", "project": 244, "scanner": "sonarqube", "version": 2 },
{ _id: "...", "project": 244, "scanner": "shellcheck", "version": 1 },
{ _id: "...", "project": 244, "scanner": "shellcheck", "version": 2 },
{ _id: "...", "project": 244, "scanner": "shellcheck", "version": 3 },
{ _id: "...", "project": 244, "scanner": "powershell", "version": 2 },
{ _id: "...", "project": 244, "scanner": "powershell", "version": 3 },
{ _id: "...", "project": 244, "scanner": "powershell", "version": 4 },
{ _id: "...", "project": 244, "scanner": "powershell", "version": 4 }
]
我想返回按扫描仪分组的最新(最高)版本的项目数:
{ scanner: "sonarqube", count: 2 }, // All items with sonarqube and version: 2
{ scanner: "shellcheck", count: 1 }, // All items with shellcheck and version: 3
{ scanner: "powershell", count: 2 } // All items with powershell and version: 4
到目前为止,我得出了这个:
db.getCollection("vulnerabilities").aggregate([
{
$match: { project_id: 422 }
},
{
$sort: { version: -1 }
},
{
$group: {
_id: "$scanner",
'count': { $first: "$version"},
}
}
])
这将返回每个组的最新(最高)版本:
sonarqube | 2 |
shellcheck | 3 |
powershell | 4 |
现在,我需要告诉 Mongo:
- 使用该版本过滤项目
- 按扫描仪分组
- 添加计数
有什么想法、建议吗?
谢谢