PHP MongoDB计数记录

时间:2017-03-09 17:59:10

标签: php mongodb database

我在php中编写了一个简单的MongoDB查询

计算过去一小时的在线总数 一切正常

但我觉得这种方式不利于表现

因为查询它自我返回所有匹配数据(因此该查询中有不需要的数据)

我需要的只是记录数

我有一个拥有数百万份文件的集合

脚本:

<?php
    // Last Online Time
    $Time = time() - 86400;

    // Connection
    $Manager = new MongoDB\Driver\Manager("mongodb://" . DB_USERNAME . ":" . DB_PASSWORD . "@" . DB_HOST . ":" . DB_PORT . "/" . DB_NAME);

    // Query
    $Query = new MongoDB\Driver\Query(['LastOnlineTime' => ['$gt' => (int) $Time]], []);

    // Result
    $Result = $Manager->executeQuery(DB_NAME . "." . $Collection, $Query);

    // Get Total Online In 1 Hour Ago
    echo count($Result->toArray());
?>

我的感觉权利吗?

1 个答案:

答案 0 :(得分:3)

我找到了一个更好的解决方案MongoDB Command

这是

<?php
// Last Online Time
$Time = time() - 86400;

// Connection
$Manager = new MongoDB\Driver\Manager("mongodb://" . DB_USERNAME . ":" . DB_PASSWORD . "@" . DB_HOST . ":" . DB_PORT . "/" . DB_NAME);

// Command
$Command = new MongoDB\Driver\Command(["count" => "account", "query" => ['LastOnline' => ['$gt' => (int) $Time]]]);

// Result
$Result = $Manager->executeCommand(DB_NAME, $Command);


//print($Result->toArray());Array ( [0] => stdClass Object ( [n] => 228598 [ok] => 1 ) //so n is our totalcount
// Get Total Online In 1 Hour Ago
echo count($Result->toArray()[0]->n);

&GT;