簡體   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