Chapter 4 $facet Lab

var pipeline =[



{
    $facet:
    {
       "rate":
       [{
           $match:
           {
               "imdb.rating":
               {
                   $ne: null
               }
           }
       }],
       "critic":
       [{
           $match:
           {
               "metacritic": 
               {
                   $ne: null
               }
               
           }
           
       }]
        
    }

},
{
    $project:
    {
        "common":
        {
            $setIntersection:
            [
                "rate", "critic"
            ]
        }
      
    }
},
{
    $limit: 10
}

];

db.movies.aggregate(pipeline);

If I run this, I get the alert that not all inputs to the $setIntersection are arrays.

I believe my problem to be with the metacritic field (I think it is a text field)… So… Here is my question.

If I select the fields outside of the $facet command, it seems that the lab is mute in that I can do all the items on their own. So… Where is my thinking wrong in this lab.

I am matching imdb.rating to the rate array and the metacritic to the critic array. Then I project an intersection… should be a no brainier… but of course I am getting a data mismatch. Suggestions?

Update… I got the lab wrong… But I looked at the solution and understand where I went wrong.

But I do have a question on the solution.

In the solution you sort on imdb.rating and metacritic by -1 (reverse order), but where I am confused is the sorting of the title.

I thought that you didn’t need to sort by title since it is projected from the prior stage. It should be part of the result set sorting on the imdb.rating and metacritic.

Another question is I was under the impression that you cannot mix 1 with -1 sort order… So… Why is it returning the right documents? Please let me know where I am wrong in this…

Thanks

You may certainly mix them. See https://docs.mongodb.com/manual/reference/operator/aggregation/sort/ and some examples that use both are presented.

If you search the forum on the above issues there are some doubts about the correct solution. It is related to the fact that you might have more than 1 movie with the rating. Let say you have 12 movies with the highest metacritic rating, which one are the top 10? I don’t know. Sorting the title might ensure a consistent result. 8-(

That makes sense… Thanks for the clarification.