【问题标题】:Using mongodb map/reduce in php在 php 中使用 mongodb map/reduce
【发布时间】:2013-12-04 06:53:26
【问题描述】:

我是 mongodb 新手,我想在连接到我的 mongo 数据库的 php 代码中使用 mongo map/reduce 函数。

我有一个名为视频的文档,其中包含大量项目,我想获取 10 个在名为“fc_total_share”的特定字段中具有最大值的项目。

顺便说一下,由于我的“视频”文档包含大量项目,您认为 map/reduce 是检索特定项目的好方法吗?如果不是,请大家帮我找到更好的方法.

【问题讨论】:

  • 太棒了。剩下的就是写一些代码了。
  • 这与 map/reduce 无关,您可以简单地按 fc_total_share 进行查找查询排序:db.videos.find().sort({"fc_total_share": -1}).limit (10);

标签: php mongodb mapreduce


【解决方案1】:

您可以使用 $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";
}

?>

只是为了展示示例代码是从这里复制的:http://php.net/manual/en/mongodb.command.php

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多