[英]What is the equivalent of PHP's mysqli_num_rows() in MongoDB?
数据库: MongoDB 3.4
编程语言: PHP 7.1
$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 个选项的回答。 我已经测试过了,它应该对你有用。
$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;
$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());
$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());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.