适用于PHP的MongoDB连接器:计算分页文档 [英] MongoDB connector for PHP: count documents for pagination
本文介绍了适用于PHP的MongoDB连接器:计算分页文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用MongoDB\Driver\Manager
通过PHP连接到MongoDB.驱动程序版本为1.6.14,我可以连接并进行查询.
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);
我尝试使用$rows->count()
和count($rows)
.第一个命令不起作用,最后一个命令返回过滤后的数据(返回20).
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).
推荐答案
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(), "\n";
}
来自此处,并根据您的情况进行调整.
Taken from here, with an adaptation to your case.
这篇关于适用于PHP的MongoDB连接器:计算分页文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文