Commit 76e995bc authored by Derick Rethans's avatar Derick Rethans

PHPLIB-376: countDocuments() throws an exception if no documents are found

parent f4b5a6f4
......@@ -152,8 +152,15 @@ class CountDocuments implements Executable
}
$cursor = $server->executeReadCommand($this->databaseName, new Command($this->createCommandDocument()), $this->createOptions());
$result = current($cursor->toArray());
$allResults = $cursor->toArray();
/* If there are no documents to count, the aggregation pipeline has no items to group, and
* hence the result is an empty array (PHPLIB-376) */
if (count($allResults) == 0) {
return 0;
}
$result = current($allResults);
if ( ! isset($result->n) || ! (is_integer($result->n) || is_float($result->n))) {
throw new UnexpectedValueException('count command did not return a numeric "n" value');
}
......
<?php
namespace MongoDB\Tests\Operation;
use MongoDB\Operation\CountDocuments;
use MongoDB\Operation\InsertMany;
use stdClass;
class CountDocumentsFunctionalTest extends FunctionalTestCase
{
public function testEmptyCollection()
{
$operation = new CountDocuments($this->getDatabaseName(), $this->getCollectionName(), []);
$this->assertSame(0, $operation->execute($this->getPrimaryServer()));
}
public function testNonEmptyCollection()
{
$insertMany = new InsertMany($this->getDatabaseName(), $this->getCollectionName(), [
['x' => 1],
['x' => 2],
['y' => 3],
['z' => 4],
]);
$insertMany->execute($this->getPrimaryServer());
$operation = new CountDocuments($this->getDatabaseName(), $this->getCollectionName(), []);
$this->assertSame(4, $operation->execute($this->getPrimaryServer()));
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment