简体   繁体   English

如何使用 PHP 中的 MongoDB\\Driver 查询获取 find() 结果的长度?

[英]How to get length of find() results with MongoDB\Driver query in PHP?

I have a MongoDB server with a collection counting hundreds of thousands of documents.我有一个 MongoDB 服务器,其中包含一个包含数十万个文档的集合。

I need to get only the number of documents matching the query filter condition using MongoDB\\Driver in PHP.我只需要在 PHP 中使用 MongoDB\\Driver 获取与查询过滤条件匹配的文档数量。

In mongo-shell I would simply do the following:mongo-shell我只需执行以下操作:

db.samples.find({"location": {$geoWithin: {$geometry: ...reference_polygon... }}}).length

The below query in PHP would return a cursor with the full list of the documents (could be thousands of docs) which I don't need, I'm only looking for the number of the samples within a specified polygon: PHP 中的以下查询将返回一个包含我不需要的完整文档列表(可能是数千个文档)的游标,我只是在寻找指定多边形内的样本数:

$query = new MongoDB\Driver\Query( 
    ["location" => ['$geoWithin' => ['$geometry' => $reference_polygon]]],
    []
);
$cursor = $dbm->executeQuery("test.samples", $query);

Even reducing projection to return a single field as _id would significantly increase the calculation time.即使减少投影以返回单个字段作为_id也会显着增加计算时间。

Is there any way to get just a scalar number of documents and avoid loading cursor results and then counting it like count($cursor->toArray()) ?有什么方法可以只获取标量数量的文档并避免加载游标结果,然后像count($cursor->toArray())那样计算它?

MongoDB Server: 4.4.1 PHP version: 7.4 OS: Ubuntu 20.04 LTS MongoDB 服务器:4.4.1 PHP 版本:7.4 操作系统:Ubuntu 20.04 LTS

So, finally, I found a way to do it using MongoDB\\Driver\\Command .所以,最后,我找到了一种使用MongoDB\\Driver\\Command

The code is below, would someone have a better proposal, please feel free to comment.代码如下,如果有人有更好的建议,请随时发表评论。

$database_name = "test";
$collection_name = "samples";
$query = new MongoDB\Driver\Query( 
    ["location" => ['$geoWithin' => ['$geometry' => $reference_polygon]]],
    []
);
$dbc = new MongoDB\Driver\Command(
    ['count' => $collection_name, "query" => (object)$query]
);
$cursor = $dbm->executeCommand($database_name, $dbc);
$n = (isset($cursor->toArray()[0]->n)) ? $cursor->toArray()[0]->n : 0;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM