Comparing 3 array elements together

I have this query to map all the values of each field… I want to create another stage so I can compare if the writer will be in director and cast fields. I don’t know how to do it using map.

db.movies.aggregate([{$match: {$and:[{writers:{$elemMatch:{$exists: true}}}, {cast:{$elemMatch:{$exists:true}}},
{directors: { $elemMatch: { $exists: true }}}]}},
{ $project:
{ _id: 0,
writers: “$writers”,
directors: “$directors”,
“uniqueCast”:
{ $map:
{
input: “$cast”,
as: “uniqueCast”,
in: “$$uniqueCast”}}}},
{ $project:
{ writers: “$writers”,
uniqueCast: “$uniqueCast”,
directors: “$directors”,
“uniqueWriters”:
{ $map:
{
input: “$writers”,
as: “uniqueWriters”,
in: “$$uniqueWriters”}}}},
{ $project:
{ “uniqueCast”: 1,
“uniqueWriters”: 1,
“uniqueDirectors”:
{ $map:
{
input: “$directors”,
as: “uniqueDirectors”,
in: “$$uniqueDirectors” }}}} ])

if you want to know what elements are common on two arrays, you can to use a mathematical concept “Set theory”

MongoDB provides the $setIntersection aggregation operator for this question

or you can use the $filter aggregation operator resulting in a complex pipeline