[英]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.