doulin8374 2017-02-08 15:33
浏览 55
已采纳

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

I'm using the MongoDB\Driver\Manager to connect to MongoDB using PHP. The driver version is 1.6.14 and I can connect and make a query.

But I need the total number of documents for my query to make the pagination:

$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);

I try with $rows->count() and with count($rows). The first command doesn't work and the last command returns the filtered data (return 20).

  • 写回答

1条回答 默认 最新

  • dongliangkeng1056 2017-02-08 15:47
    关注

    Use executeCommand method. Try something like the following code:

    $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(), "
    ";
    }
    

    Taken from here, with an adaptation to your case.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 关于加载卡的问题有能知道这个要怎么处理吗?
  • ¥100 rtmpose姿态评估
  • ¥15 java 通过反射找路径下的类,打包后就找不到
  • ¥15 通联支付网上收银统一下单接口
  • ¥15 angular有偿编写,
  • ¥15 centos7系统下abinit安装时make出错
  • ¥15 hbuildex运行微信小程序报错
  • ¥15 关于#python#的问题:我知道这个问题对你们来说肯定so easy
  • ¥15 wpf datagrid如何实现多层表头
  • ¥15 为啥画版图在Run DRC会出现Connect Error?可我Calibre的hostname和计算机的hostname已经设置成一样的了。