Chapter 4 lab: $setIntersection returning empty

Hi so i actually got the correct answer except my $setIntersection was returning an empty array. It was upon manual inspection I can see the answer. When I compare my pipeline to the asnwer there almost identical and im wondering why mine was not showing the result of the $setIntersection.
I am hesitant to share my solution as I don’t want to make it to easy for someone else.

Real learners won’t try to peek at a potential answer because they want to learn.

Cheaters that only want to show a certificate of completion will cheat any way. They actually cheat them self more because they won’t have acquire the knowledge. That will show eventually.

The most common mistake I saw in a pipeline, is to access a projected (in $project, $addField or $set) field in the same stage as it is projected in an expression for another field. The projected/added/set field is only accessible in the next stage.

2 Likes

agreed. I was thinking it was something to do with the $project in the solution provided I think project came before the faucet. Im just curious if that is the reason why because the fields still show up as expected.

db.movies.aggregate([
  {$match: {$and: [
    { "imdb.rating": {$gte: 0}},
    { "metacritic": {$gte: 0}},
  ]}},
  {$facet: {
    topTenIMDB: [
      {$sort: {"imdb.rating": -1, title: 1}},
      {$limit: 10},
      {$project: {title: 1, 'imdb.rating': 1}},
    ],
    toptenMetaCritic: [
      {$sort: {"metacritic": -1, title: 1}},
      {$limit: 10},
      {$project: {title: 1, 'metacritic': 1}},
    ],
  }},
  {$project: {topTenIMDB: 1, toptenMetaCritic: 1, result:{$setIntersection:       
    ['$topTenIMDB','$toptenMetaCritic']}}},
])

Your issue is not the most common mistake.

Two objects in 2 different arrays must be strictly equals to be in the intersection. To be strictly equals they must have the same fields with the same values in the same order.

The objects out of your topTenIMDB facet have the field imbd.rating but none of the objects from toptenMetaCritic have it. Similarly, all objects out of toptenMetaCritic have the field metacritic while none of the ones from topTenIMDB have it.

So while some objects from both facets refer to the same movies (by title), they are all different.

2 Likes

That makes a lot of sense. Thanks for this explanation and refactoring the example not used to this interface yet hehe.

1 Like

@Stennie did the refactoring. I do not have those rights.

1 Like