MongoDB(PHP) - MapReduce - 使用相同的ID

时间:2015-12-18 18:26:19

标签: php mongodb mapreduce

我有一个名为 requests 的集合,其中包含以下原型的文档:

{
  "_id": {
    "$id": "56295368ef2b8e5458000029"
  },
  "title": "Hardcoded Name",
  "requestorId": "dve34gegrgeefdsfewe"
}

这些文档的requestorId用户集合的id(不是_id Mongo对象ID)相关联,其文档遵循以下原型:

{
  "_id": {
    "$id": "86235288ef2gif5458000027"
  },
  "id": "dve34gegrgeefdsfewe",
  "name": "John Doe"
}

我需要能够在请求集合上运行find(),并获取与每个请求文档中的name相关联的requestorId。我通常会做的很明显:在find()上运行requests,然后在循环浏览每个文档时,对用户进行后续查询,其中id = [requestorId (really "id" in users collection)],但是我需要能够按照与每个requestorId关联的名称对整个请求集合进行排序,然后使用skip()& limit()。这应该很简单,但我似乎无法弄明白......到目前为止,这是我的代码,灵感来自https://www.noppanit.com/merge-documents-two-collections-together-mongodb/

$m = new MongoClient(); // connect
$db = $m->{"database"};

// construct map and reduce functions
$eventRequest_map = new MongoCode("function() { 
    emit(this.requestorId, {\"requestorId\" : this.requestorId}) 
}");
$user_map = new MongoCode("function() { 
    emit(this.id, {\"name\" : this.name})
}");


$reductionFunction = new MongoCode("function(key, values) {
    var result = {
        \"requestorId\" : \"\",
        \"name\" : \"\"
    };

    return result;
}");

$sales = $db->command(array(
    'mapreduce' => "requests", 
    'map' => $eventRequest_map,
    'reduce' => $reductionFunction,
    'query' => array(),
    'out' => 'joined'));

$sales = $db->command(array(
    'mapreduce' => "users", 
    'map' => $user_map,
    'reduce' => $reductionFunction,
    'query' => array(),
    'out' => 'joined'));


$collection = $db->joined;

$cursor = $collection->find();
$outputJoined = array();
foreach($cursor as $doc){
    $outputJoined[] = $doc;
}
echo json_encode($outputJoined);

0 个答案:

没有答案