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

Return all document occurrences in mongoose $group aggregate query

My current query

aggregate([
                    { $match : { treatment: 'no treatment',baseScore:{$gte:9}} },
                    {"$group":{
                        "_id":{"cveDataMetaIds":"$cveDataMetaIds","baseScore":"$baseScore"},
                        "count":{"$sum":1}
                      }
                    }
                    ])

returns this result

[{
    _id: {
      cveDataMetaIds: 'CVE-2021-30820',
      baseScore: 9.8
    },
    count: 2
  },
  {
    _id: {
      cveDataMetaIds: 'CVE-2021-33757',
      baseScore: 9.8
    },
    count: 1
  }

]

I am wondering if it’s possible to print it like this so that it would show the count for example count=2 and the two documents as well in an array below it ?

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

[{
    _id: {
      cveDataMetaIds: 'CVE-2021-30820',
      baseScore: 9.8
    },
    count: 2,
    data:[
    {first occurrence data},
    {second occurrence data}
    ]
  }
]

>Solution :

You can collect the entire document with pushing it into a field array.
$$ROOT will give you the "looped" document.
Untested!

aggregate([
                    { $match : { treatment: 'no treatment',baseScore:{$gte:9}} },
                    {"$group":{
                        "_id":{"cveDataMetaIds":"$cveDataMetaIds","baseScore":"$baseScore"},
                        "count":{"$sum":1},
                        "data" : {$push : "$$ROOT"}
                      }
                    }
                    ])
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