-3

当按发布目标、类型和状态对 80'000 个帖子进行分组时,下面的代码需要 30 秒。

有什么明显的方法可以改善加载时间吗?

            //by publish target
            $collection = $this->mongoDB->Post;
            $keys = array('publish_target' => true);
            $initial = array("count" => 0);
            $reduce = "function (obj, prev) { prev.count++; }";
            $result = $collection->group($keys, $initial, $reduce);
            foreach ($result['retval'] as $value) {
                $this->results['Post']['publish_target'][] = array('key' => $value['publish_target'], 'value' => $value['count']);
            }

        // by type
        $collection = $this->mongoDB->Post;
        $keys = array('type' => true);
        $initial = array("count" => 0);
        $reduce = "function (obj, prev) { prev.count++; }";
        $result = $collection->group($keys, $initial, $reduce);
        foreach ($result['retval'] as $value) {
            $this->results['Post']['type'][] = array('key' => $value['type'], 'value' => $value['count']);
        }

        // by status
        $collection = $this->mongoDB->Post;
        $keys = array('status' => true);
        $initial = array("count" => 0);
        $reduce = "function (obj, prev) { prev.count++; }";
        $result = $collection->group($keys, $initial, $reduce);
        foreach ($result['retval'] as $value) {
            $this->results['Post']['status'][] = array('key' => $value['status'], 'value' => $value['count']);
        }

固定的

            $ops = array(
                array(
                    '$group' => array(
                        '_id' => array($arrayKey => '$'.$arrayKey),
                        'count' => array('$sum' => 1)
                    )
                )
            );
            $retrieved = $collection->aggregate($ops);
4

1 回答 1

0

首先,这不是您正在运行的单个聚合,您基于前一个的输出分别运行三个,并且不清楚为什么要这样做,而不是仅在单个聚合中按 publish_target、类型和状态进行分组。

其次,您使用的是通过 Javascript 实现的 group() 函数,而不是在服务器上本地运行的聚合框架。您需要的唯一查询/命令是:

db.post.aggregate({$group:{
          _id: { publish_target : "$publish_target" },
          count: {$sum : 1}
} );

您现在将在服务器上一次性获得这些计数。

于 2013-06-07T03:17:49.257 回答