MongoDB: Aggregate match with reference, filter & sort by count

Viewed 14

What I'm trying to achieve is, get the genres that have stations in Canada & sort the genres by the total available stations in ca

Parent Data

{
    "_id" : ObjectId("629190bc8a89c22d6dd0a1ec"),
    "name" : "106.5 fm",
    "stations" : [
        ObjectId("62979c7c154494e509356654"),
        ObjectId("6291931f40815f4a014f667f"),
    ],
    "__v" : NumberInt(0),
    "total_stations" : NumberInt(4)
}

Child Data

{
    "_id" : ObjectId("62979c7c154494e5093565c5"),
    "name" : "_80s_Radio",
    "genres" : [
        ObjectId("629190bc8a89c22d6dd0a1ed"),
    ],
    "country" : "The United States Of America",
}
{
    "_id" : ObjectId("62979c7c154494e509356654"),
    "name" : "_Radio Energy Classic (Italy)",
    "genres" : [
        ObjectId("629190bc8a89c22d6dd0a1ec"),
    ],
    "country" : "Canada",
}

This is what I have tried so far:

db.categories.aggregate([
    {
      $lookup: {
        from: 'radio_stations',
        let: { gid: '$stations' },
        pipeline: [
          {
            $match: {
              $expr: {
                $and: [
                  { $in: ['$_id', '$$gid'] },
                  { $eq: ['$country', 'Canada'] },
                ],
              },
            },
          },
        ],
        as: 'radio_stations',
      },
    },
  ]);
0 Answers
Related