[英]What is the equivalent of PHP's mysqli_num_rows() in MongoDB?
Database : MongoDB 3.4数据库: MongoDB 3.4
Programming Language : PHP 7.1编程语言: PHP 7.1
Library : PHP library of MongoDB 1.2.0库: MongoDB 1.2.0 的PHP 库
$result = $connection->db->collection->find($filter, $options);
In MySQL, you do this:在 MySQL 中,您可以这样做:
$number_of_rows = mysqli_num_rows($result);
When trying things out and doing some research, I've tried this:在尝试和做一些研究时,我试过这个:
$number_of_rows = $result->count();
It returns this error since it's part of the legacy (not included in the MongoDB driver ):它返回此错误,因为它是遗留的一部分(未包含在MongoDB 驱动程序中):
Error: Call to undefined method MongoDB\Driver\Cursor::count()
When I tried using count() or sizeof(), the result is always 1.当我尝试使用 count() 或 sizeof() 时,结果始终为 1。
$number_of_rows = count($result);
$number_of_rows = sizeof($result);
How should it be done properly in this version (or the latest version 3.6) of MongoDB without having to iterate a $count variable inside a for-loop?应该如何在 MongoDB 的这个版本(或最新版本 3.6)中正确完成,而不必在 for 循环中迭代 $count 变量?
I expanded @Yury-Fedorov's answer to these 3 options.我扩展了@Yury-Fedorov 对这 3 个选项的回答。 I have tested this and it should work on your end.我已经测试过了,它应该对你有用。
$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());
You should be able to use $collection->count()
method instead of $result->count()
:您应该能够使用$collection->count()
方法而不是$result->count()
:
$query = []; // your criteria
$collection->count($query);
Take a look at this discussion or at my answer to another MongoDB count with PHP question, which is not exactly the same is this one.看看这个讨论或在我的回答与PHP的问题,这是不完全一样的是这彼此的MongoDB计数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.