1

I'm trying to adapt the answer(Map Reduce Approach) provided in this question into php:

Does MongoDB's $in clause guarantee order

Here's what I have done, I get no errors, but I receive no results:

$items = array('523fe7e00000000000000000', '5230e7e00000000000000000', '5240e1e00000000000000000');

$items_converted = array();
foreach($items as $an_item){
    $items_converted[] = new MongoID($an_item);
}

$map = new MongoCode('
    function () {
        var order = inputs.indexOf(this._id);
        emit( order, { doc: this } );
    }
');
$finalize = new MongoCode('
    function (key, value) {
        return value.doc;
    }
');
$results = $db->command(array(
    'mapreduce' => 'template_items',
    'map' => $map,
    'out' => array('inline' => 1),
    'query' => array('_id' => array('$in' => $items_converted)),
    'scope' => array('inputs' => $items_converted),
    'finalize' => $finalize
));

foreach($results as $row){
    echo $row['title'];
}

The main goal of this is to sort the results in the exact order as the array containing the IDs. I can get it to work in command line, just having trouble adapting it into php.

Community
  • 1
  • 1
user2430227
  • 303
  • 1
  • 3
  • 13
  • what exactly is the problem? It's mapReduce so the code will be entirely JavaScript. Nothing to adapt there. Why do you have a finalize method and also why emit under a doc key? Just use `this` as it's an object. Just guessing that your "problem" is that the document no longer looks the same, but that is just how mapReduce works. – Neil Lunn Jan 28 '15 at 02:18
  • I think it's overkill to use map/reduce, which takes a global lock, in order to get the results back in the same order as the `$in` array. Why do you need the results back in the same order? Could you just do the sorting in the client? – wdberkeley Jan 28 '15 at 17:52

0 Answers0