1

I need the pipeline to match documents where field 'modelName' is equal to 'movies' or 'tv_shows'. I tried the code below but it matches only 'tv_shows' and ignores 'movies'.

$match = array('$match' => array('modelName' => 'movies', 'modelName' => 'tv_shows'));

Whole script:

<?php

   $connection = new MongoClient;
   $collection = $connection -> selectDB("getglue") -> selectCollection("gg");
   MongoCursor::$timeout = -1;

   $match = array('$match' => array('modelName' => 'movies', 'modelName' => 'tv_shows'));
   $group = array('$group' => array('_id' => '$title', 'total' => array('$sum' => 1)));
   $sort = array('$sort' => array('total' => -1));
   $limit = array('$limit' => 7);
   $pipeline = array($match, $group, $sort, $limit);

   $out = $collection -> aggregate($pipeline);

   echo json_encode($out, JSON_PRETTY_PRINT);

?>

1 Answer 1

1

Make use of the $or operator:

$match = array('$match' => 
                 array('$or' => array(array("modelName" => "movies"),
                                array("modelName" => "tv_shows"))
                      )
     );

An array in PHP is actually an ordered map. A map can have only one value for any key, and the last added value will override any previous values for the same key. So, in the below, tv_shows which is the last added value for the key - modelName will be associated as the key's only value. And that is why you get the results only for modelname of tv_shows.

'$match' => array('modelName' => 'movies', 'modelName' => 'tv_shows')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.