Home > OS >  Mongoose group and count by item in array
Mongoose group and count by item in array

Time:11-22

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 :

[{
    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!

CodePudding user response:

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