Using mongodb map/reduce in php

流过昼夜 提交于 2019-12-25 17:16:37

问题


I'm new to mongodb and I want to use mongo map/reduce function in my php codes connected to my mongo database.

I have a document named videos with a large number of items, I want to get 10 items that have the largest values in specific field named "fc_total_share".

And by the way, as my "videos" document has really large number of items, do you think that map/reduce is a good way to retrieve specific items and if not would you guys please help me to find a better way.


回答1:


You can do this using $db->command()

<?php

// sample event document
$events->insert(array("user_id" => $id, 
    "type" => $type, 
    "time" => new MongoDate(), 
    "desc" => $description));

// construct map and reduce functions
$map = new MongoCode("function() { emit(this.user_id,1); }");
$reduce = new MongoCode("function(k, vals) { ".
    "var sum = 0;".
    "for (var i in vals) {".
        "sum += vals[i];". 
    "}".
    "return sum; }");

$sales = $db->command(array(
    "mapreduce" => "events", 
    "map" => $map,
    "reduce" => $reduce,
    "query" => array("type" => "sale"),
    "out" => array("merge" => "eventCounts")));

$users = $db->selectCollection($sales['result'])->find();

foreach ($users as $user) {
    echo "{$user['_id']} had {$user['value']} sale(s).\n";
}

?>

Just to show example Code is copied from here : http://php.net/manual/en/mongodb.command.php



来源:https://stackoverflow.com/questions/20368948/using-mongodb-map-reduce-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!