【问题标题】:How to get cursor result count using the MongoDB PHP extension如何使用 MongoDB PHP 扩展获取游标结果计数
【发布时间】:2016-08-12 02:02:40
【问题描述】:

mongo PHP 扩展已弃用,取而代之的是 mongodb 扩展。此扩展名与mongo-php-library 一起使用。

在旧的扩展中,可以使用MongoCursor::count() 从游标中获取结果计数。但是,新游标MongoDB\Driver\Cursor 没有这样的方法。对 MongoDB 执行查询后获取结果数量的新方法是什么?

【问题讨论】:

  • 有没有办法在不从 Mongo 服务器获取所有结果的情况下获取计数结果?我只需要计数。

标签: php mongodb php-mongodb


【解决方案1】:

你可以这样做

Model::count(array($whereClause));

$whereClause 基本上是您的搜索条件。

否则,如果您的查询返回一个数组,您可以这样做

$data = Model::find(array($whereClause));
$total = count($data);

【讨论】:

  • 但这意味着当我也想得到实际结果时,我必须执行两个查询。
  • @ChinLeung "Model::" 是什么?
  • @Drumnbass 这是班级的名字。
【解决方案2】:

我使用此代码。

$query = ["hello" => "world"];
$command = new MongoDB\Driver\Command(["count" => "collection", "query" => $query]);
try {
    $result = $mongo->executeCommand("mydb", $command);
    $res = current($result->toArray());
    $count = $res->n;
    echo $count;
} catch (MongoDB\Driver\Exception\Exception $e) {
    echo $e->getMessage(), "\n";
}

【讨论】:

  • 这是连同查询一起提取所有数据......还是只是计算响应?我的文档很大,我试图避免整个文档集都必须通过网络来计算它们。
  • @lowcrawler 只返回一个数字,实际上这段代码的工作原理与 db.runCommand( { count: 'collection' } ) 并返回 { "n" : 26, "ok" : 1 } .
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-08-12
  • 1970-01-01
  • 1970-01-01
  • 2011-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多