数据库: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 。
答案 0 :(得分:0)
您应该可以使用$collection->count()
方法代替$result->count()
:
$query = []; // your criteria
$collection->count($query);
答案 1 :(得分:0)
我扩展了@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());