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

Mongoose group and count by item in array

Below is my mongodb structure:

[{
    countries: ["US"],
    type: "4"
  },
  {
    countries: ["IN"],
    type: "4"
  },
  {
    countries: ["US"],
    type: "4"
  }
]

Note : countries array has just one item in the array for this case

And I expect to group and count where type === 4 so that the result to be :

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

[{
    countries: ["US"],
    count: 2
},{
    countries: ["IN"],
    count: 1
}]

Well, I tried using aggregation like this, but I think I got it wrong:

const aggregatorOpts = [{
  $group: {
    _id: "$countries",
    count: { $sum: 1 }
  }
}]

Model.aggregate(aggregatorOpts).exec()

Any help regarding how to do the aggregation probably is appreciated.

Thanks in advance!

>Solution :

Is this what you want? You need to do a $match first.
https://mongoplayground.net/p/UuOF53E44tG

db.collection.aggregate([
  {
    $match: {
      type: {
        $eq: "4"
      }
    }
  },
  {
    $group: {
      _id: "$countries",
      count: {
        $sum: 1
      }
    }
  }
])
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