繁体   English   中英

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

[英]What is the equivalent of PHP's mysqli_num_rows() in MongoDB?

规格

数据库MongoDB 3.4

编程语言PHP 7.1

MongoDB 1.2.0 的PHP 库

示例代码

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

在 MySQL 中,您可以这样做:

$number_of_rows = mysqli_num_rows($result);

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

$number_of_rows = $result->count();

它返回此错误,因为它是遗留的一部分(未包含在MongoDB 驱动程序中):

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 变量?

同样的问题,但这里的答案已经过时

我扩展了@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());

您应该能够使用$collection->count()方法而不是$result->count()

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

看看这个讨论或在我的回答与PHP的问题,这是不完全一样的是这彼此的MongoDB计数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM