MongoDB connector for PHP: count documents for pagination

I’m using the MongoDBDriverManager 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 MongoDBDriverManager("mongodb://localhost:27017");
$filter = [];
$filter["brand"] = $_GET["brand"];
$options = ["skip" => ($pag-1)*$reg_pag , "limit" => $reg_pag];
$query = new MongoDBDriverQuery($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).

Answer

Use executeCommand method. Try something like the following code:

$mongo = new MongoDBDriverManager("mongodb://localhost:27017");
// search params
$query = ["brand" => $_GET["brand"]];
// define a command - not only a regular query
$command = new MongoDBDriverCommand(["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 (MongoDBDriverExceptionException $e) {
    echo $e->getMessage(), "n";
}

Taken from here, with an adaptation to your case.

Leave a Reply

Your email address will not be published. Required fields are marked *