Home > other >  Return all document occurrences in mongoose $group aggregate query
Return all document occurrences in mongoose $group aggregate query

Time:08-18

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 ?

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

CodePudding user response:

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"}
                      }
                    }
                    ])
  • Related