Lab: $unwind having trouble counting re-occurring cast members

I’ve got my script to filter for movies in english, unwind all the cast members, and group according to cast and title while finding average imdb.ratings. My only issue I believe is, I don’t know how to count how many times a name is repeated. I’ve tried $sum: 1 and $count but am getting errors.

var pipeline = [
  {
    $match: { languages: "English"},
  },

  { 
    $unwind: "$cast" 
  },

  {

    $group: { 
      _id: {
        cast: "$cast", 
        title: "$title"
      },
      average_rating: { $avg: "$imdb.rating"}
    }
  },

  { 
    $count: "cast"
  }

]

gives me the total amount of unwinded cast members for every movie. 119,462. This does not help me identify how many times each cast member shows up in movies and I’m stuck right here.

Hi @Douglas_Sourile, welcome to the community. :wave:
You are halfway there already, but it seems like your implementation of $group stage is wrong, you don’t have to group by title.
As the question says:

We’d like to calculate how many movies every cast member has been in and get an average imdb.rating for each cast member.

Hence "$cast" is enough to group.
Also, you can add multiple accumulators, like $avg, $sum, $last, $max etc. in a single $group stage, so I guess you got the idea on how to proceed ahead.
All the best.

Also, please note that whenever you post a query/pipeline/command please format them with three backticks, at the start and the end of the code, it makes it easier to read for the fellow community members and learners, and don’t forget to wrap your code with the [spoiler] tag whenever you are posting a potential answer.

In case you have any doubts, please feel free to reach out to us.

Thanks & Regards.
Sourabh Bagrecha,
Curriculum Services Engineer