How to use $in on a document's field

Hello all,

I am trying to match all the documents, where there is no element in the cast which also appears in the writers.
I am using the following 2 stages: the First one is to ensure that arrays are exits, and the second is the checking itself

{
$match: { writers: { $elemMatch: { $exists: true } },
cast: { $elemMatch: { $exists: true } },
},
},
{
$match: {
writers:
{
$elemMatch: {
$nin: “$cast”
}
}
}
}

But, I get an error “$nin needs an array”, what I do wrong?

@Egor_49591

You will have to check you syntax on $match. Please refer to the example from the docs.

db.articles.aggregate([
  { 
    $match: {
      score: { $gt: 70, $lt: 90 }, 
      views: { $gte: 1000 },
    }
  }
]);

I’ve tried to run a simple aggregation
{
cast: { $in: “$directors” }
}
But it still gives an error “$in needs an array”

I’ve solved this task. To do it, you need $setIntersection operator https://docs.mongodb.com/manual/reference/operator/aggregation/setIntersection/ and some additional stages

1 Like