【问题标题】:What is the equivalent of PHP's mysqli_num_rows() in MongoDB?什么是 MongoDB 中 PHP 的 mysqli_num_rows() 的等价物?
【发布时间】:2017-12-28 08:34:38
【问题描述】:

规格

数据库MongoDB3.4

编程语言PHP7.1

PHP library of MongoDB1.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);

在这个版本(或最新版本 3.6)的 MongoDB 中应该如何正确完成,而不必在 for 循环中迭代 $count 变量?

同样的问题,但答案已过时here

【问题讨论】:

  • @AlivetoDie 在命令行中,是的,是的,您甚至可以过滤查找需要计数的内容。但是我已经发布了上面的示例代码,表明需要在 find() 执行后检索结果数。
  • 希望这会有所帮助。 stackoverflow.com/a/12098786/4903314
  • @MikeDaVinci 这与我在问题中发布的链接相同(底部为斜体)。它已经过时了。答案是针对旧版本的(我还在问题中发布了指向遗留代码文档的链接)。

标签: php mongodb


【解决方案1】:

我扩展了@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());

【讨论】:

    【解决方案2】:

    您应该可以使用$collection->count() 方法而不是$result->count()

    $query = []; // your criteria
    $collection->count($query);
    

    查看this 讨论或我的answer 到另一个 MongoDB 计数与 PHP 问题,这与这个不完全相同。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-23
      • 1970-01-01
      • 2012-09-14
      • 2011-10-13
      相关资源
      最近更新 更多