MongoDB中PHP的mysqli_num_rows()相当于什么?

时间:2017-12-28 08:34:38

标签: php mongodb

规范

数据库MongoDB 3.4

编程语言PHP 7.1

图书馆PHP library of MongoDB 1.2.0

示例代码

$result = $connection->db->collection->find($filter, $options);

在MySQL中,你这样做:

$number_of_rows = mysqli_num_rows($result);

在尝试并做一些研究时,我试过这个:

$number_of_rows = $result->count();

它返回此错误,因为它是legacy的一部分(未包含在MongoDB driver中):

Error: Call to undefined method MongoDB\Driver\Cursor::count()

当我尝试使用count()或sizeof()时,结果始终为1.

$number_of_rows = count($result);

$number_of_rows = sizeof($result);

如何在MongoDB的这个版本(或最新版本3.6)中正确完成,而不必在for循环中迭代$ count变量?

同样的问题,但过时的答案here

2 个答案:

答案 0 :(得分:0)

您应该可以使用$collection->count()方法代替$result->count()

$query = []; // your criteria
$collection->count($query);

使用PHP问题查看this讨论或我的answer到另一个MongoDB计数,这与此问题完全相同。

答案 1 :(得分:0)

我扩展了@Yury-Fedorov对这3个选项的回答。我已经对此进行了测试,它应该适用于你。

选项1

$filter = ['field' => 'value'];
$db = new \MongoDB\Driver\Manager('mongodb://localhost:27017');
$command = new \MongoDB\Driver\Command(['count' => $collection_name, 'query' => $filter]);
try {
    $cursor = $db->executeCommand($database_name, $command);
} catch (\MongoDB\Driver\Exception\Exception $e) {
    $error_message = $e->getMessage();
}
$count = $cursor->toArray()[0]->n;

选项2

$filter = ['field' => 'value'];
$options = ['option' => 'value'];
$db = new \MongoDB\Driver\Manager('mongodb://localhost:27017');
$query = new \MongoDB\Driver\Query($filter, $options);
try {
    $cursor = $db->executeQuery("$database_name.$collection_name", $query);
} catch (\MongoDB\Driver\Exception\Exception $e) {
    $error_message = $e->getMessage();
}
$count = count($cursor->toArray());

选项3

$filter = ['field' => 'value'];
$options = ['option' => 'value'];
$db = new \MongoDB\Client ('mongodb://localhost:27017');
try {
    $cursor = $db->{$database_name}->{$collection_name}->find($filter, $options);
} catch (\MongoDB\Driver\Exception\Exception $e) {
    $error_message = $e->getMessage();
}
$count = count($cursor->toArray());