MongoDB:获得不同组之间价值最高的文档计数
我面临MongoDB的问题。我需要计算由另一个字段最高值的字段分组的所有文档。
我给您一个例子:
{ id: 1, scanner: 'bandit', severity: 'low', version: 1 },
{ id: 2, scanner: 'bandit', severity: 'low', version: 1 },
{ id: 3, scanner: 'bandit', severity: 'medium', version: 1 },
{ id: 4, scanner: 'bandit', severity: 'medium', version: 2 },
{ id: 5, scanner: 'bandit', severity: 'high', version: 2 },
{ id: 6, scanner: 'semgrep', severity: 'critical', version: 2 },
{ id: 7, scanner: 'semgrep', severity: 'critical', version: 3 },
{ id: 8, scanner: 'semgrep', severity: 'info', version: 4 },
{ id: 9, scanner: 'semgrep', severity: 'info', version: 4 },
在这种情况下,我们有两个扫描仪(BANDIT
和semgrep
)。
“强盗”文档的最高版本是2
,而“ semgrep”文档的最高版本是4
。
我需要根据扫描仪和严重性对它们进行分组,具体取决于它们的最高版本,忽略了以前的版本,并计算它们。
结果应该与此相似:
[
{ "scanner": "bandit", "severity": "medium", "count": 1, "version": 2 },
{ "scanner": "bandit", "severity": "high", "count": 1, "version": 2 },
{ "scanner": "semgrep", "severity": "info", "count": 2, "version": 4 }
]
我正在挣扎,到达我无法忽略前版本的时候。任何帮助都将受到赞赏。
非常感谢
I am facing a problem with MongoDB. I need to count all documents grouped by fields with the highest value of another field.
I'll give you an example:
{ id: 1, scanner: 'bandit', severity: 'low', version: 1 },
{ id: 2, scanner: 'bandit', severity: 'low', version: 1 },
{ id: 3, scanner: 'bandit', severity: 'medium', version: 1 },
{ id: 4, scanner: 'bandit', severity: 'medium', version: 2 },
{ id: 5, scanner: 'bandit', severity: 'high', version: 2 },
{ id: 6, scanner: 'semgrep', severity: 'critical', version: 2 },
{ id: 7, scanner: 'semgrep', severity: 'critical', version: 3 },
{ id: 8, scanner: 'semgrep', severity: 'info', version: 4 },
{ id: 9, scanner: 'semgrep', severity: 'info', version: 4 },
In this case we have two scanners (bandit
and semgrep
).
The highest version for "bandit" documents is 2
while the highest version for "semgrep" documents is 4
.
I need to group them by scanner and severity depending on their highest version, ignoring the previous versions, and count them.
The result should be similar to this:
[
{ "scanner": "bandit", "severity": "medium", "count": 1, "version": 2 },
{ "scanner": "bandit", "severity": "high", "count": 1, "version": 2 },
{ "scanner": "semgrep", "severity": "info", "count": 2, "version": 4 }
]
I'm struggling, I arrive to a point when I cannot ignore the former versions. Any help is appreciated.
Many thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用MongoDB v5.0+,
您可以使用
$ setWindowfields
来计算扫描仪
分组的等级。然后,具有最高等级(IE等级= 1),您可以执行另一个$组
和计数。这是 mongo Playground 供您参考。
With MongoDB v5.0+,
you can use
$setWindowFields
to compute rank for thescanners
grouping. Then, with the highest rank(i.e. rank = 1), you can do another$group
and count.Here is the Mongo Playground for your reference.