Show Actors with the longest working career

Hello , I have a collection in which I want to show the 5 actors whose career has been the longest. To do this, you must show when your career began, when it ended and how many years you have worked. Before I need to filter to eliminate those actors called “Undefined”.

Hi @Jose_jimenez1 and welcome to the MongoDB community forum!!

Based on the sample data provided and to achieve the desired output, you could perform the following steps:

  1. $unwind the cast array, which would create object for each of the actors present in the collection.
  2. $group the documents based on cast and calculate the min_year and max_year from the $year fields using $min and $max operators.
  3. Once you have the min_year and ma_year, using $addFields you can find the duration for which they have worked for using the $subtract operator.
  4. Finally sort the durations in descending and use limit to find the top 5 actors with max duration they have worked for.

Please note that the above steps would work, if the year field is an integer, else, an extra field to to convert the data type to integer would be needed.

You can refer the documentation to convert a string field to an Integer using toInt to convert the field datatype.

I believe, you have two other posts:

  1. Show year with more movies
  2. Group + show total number of actors
    which also would be solved with the similar approach.

Let us know if the aggregation pipeline works for the above queries.
If not, let us know the aggregation pipeline you tried and we can try to help you further.

Best Regards
Aasawari

1 Like