用于PHP的MongoDB连接器:计算分页文档

时间:2017-02-08 15:33:51

标签: php mongodb

我正在使用MongoDB\Driver\Manager使用PHP连接到MongoDB。驱动程序版本是1.6.14,我可以连接并进行查询。

但是我需要查询的总文档数来进行分页:

$reg_pag = 20;
$pag = $_GET["pag"];

$mng = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$filter = [];
$filter["brand"] = $_GET["brand"];
$options = ["skip" => ($pag-1)*$reg_pag , "limit" => $reg_pag];
$query = new MongoDB\Driver\Query($filter, $options);
$rows = $mng->executeQuery("carsdb.cars", $query);

我尝试$rows->count()count($rows)。第一个命令不起作用,最后一个命令返回过滤后的数据(返回20)。

1 个答案:

答案 0 :(得分:0)

使用executeCommand方法。尝试类似下面的代码:

$mongo = new MongoDB\Driver\Manager("mongodb://localhost:27017");
// search params
$query = ["brand" => $_GET["brand"]];
// define a command - not only a regular query
$command = new MongoDB\Driver\Command(["count" => "cars", "query" => $query]);
try {
    // execute the command here on your database
    $result = $mongo->executeCommand("carsdb", $command);
    $res = current($result->toArray());
    $count = $res->n;
    echo $count;
} catch (MongoDB\Driver\Exception\Exception $e) {
    echo $e->getMessage(), "\n";
}

取自here,改编自你的案件。

相关问题