我是mongodb的新手,我想在连接到我的mongo数据库的php代码中使用mongo map / reduce函数。
我有一个名为带有大量项目的视频的文档,我希望得到10个在特定字段中具有最大值的项目,名为" fc_total_share"。
顺便说一下,正如我的视频"文件有很多项目,你认为map / reduce是检索特定项目的好方法,如果没有,请你帮我找一个更好的方法。
答案 0 :(得分:4)
您可以使用 $ db->命令()
执行此操作<?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";
}
?>
仅显示示例代码从此处复制:http://php.net/manual/en/mongodb.command.php