Question in $setIntersection

$setIntersection - Takes two or more arrays and returns an array that contains the elements that appear in every input array.

Please explain the output for the below aggregation -
db.movies.aggregate([
{
$project: { _id: 0,
a: [‘A’,‘B’,‘C’],
b : [‘B’,‘D’],
commonToBoth: {$setIntersection: ["$a", “$b”]}
}
},
{
$limit : 1
}
]);

Expected Output - { “a” : [ “A”, “B”, “C” ], “b” : [ “B”, “D” ], “commonToBoth” : [“B”] }
Received Output - { “a” : [ “A”, “B”, “C” ], “b” : [ “B”, “D” ], “commonToBoth” : null }
I may be missing something here, Kindly explain why is common element B not returned here.

Thanks.

In the context of this aggregation, both $a and $b are null when evaluated in the $project. Try adding another stage, like the following:

db.movies.aggregate([
  { 
    $project: {
      _id: 0,
      a: ["A", "B", "C" ],
      b: ["B", "D"],
    }
  },
  {
    $addFields: {
      commonToBoth: {
        $setIntersection: ["$a", "$b"]
      }
    }
  }
])

If you want to use newly defined variables within a stage, look into the $let expression!

Hope this helps.

Nathan

Thanks Nathan, that was very helpful… :blush:

In the above example, I added a types field like below:

db.movies.aggregate([
{
$project: {
_id: 0,
a: [“A”, “B”, “C” ],
b: [“B”, “D”],
}
},
{
$addFields: {
commonToBoth: {
$setIntersection: ["$a", “$b”]
},
types: {$isArray: “$commonToBoth”}
}
}
])

I expect the types to be “true” as the return value of $setIntersection is an array. But, I am getting all false. Can somebody clarify… Thank you.

@Balaji_V_80301

In case you did not notice, you are adding a new question to a post that was answered almost a year ago. If the information here solves your problem, as it did for @Sampreet_83625 , that’s fine. But if you have a new question, create a new post. Thanks.