问题
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