Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

MongoDB filter by retrieved value in group

I have this collection in 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 }
]

I would like to return the number of items, grouped by scanner, with the latest (highest) version:

{ 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

So far, I came out with this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

db.getCollection("vulnerabilities").aggregate([
{
    $match: { project_id: 422 }
},
{
    $sort: { version: -1 }
},
{
    $group: {
        _id: "$scanner",
        'count': { $first: "$version"},
    }
}
])

This returns the latest (highest) version for each group:

sonarqube  | 2 |
shellcheck | 3 |
powershell | 4 |

Now, I need to tell Mongo:

  • filter the item with that version
  • group by scanner
  • add the count

Any ideas, suggestion?

Thanks

>Solution :

The simplest way would be to get the count first, before sorting by version, perhaps:

db.getCollection("vulnerabilities").aggregate([
{
    $match: { project_id: 422 }
},
{   
    $group:{
       _id: { scanner: "$scanner", version: "$version"},
       count: { $sum: 1 }
    }
},
{
    $sort: { "_id.version": -1 }
},
{
    $group: {
        _id: "$_id.scanner",
        count: { $first: "$count" },
        version: { $first: "$_id.version" }
    }
}
])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading