PHP MongoDB Count Records

二次信任 提交于 2021-02-05 06:52:29

问题


I've wrote a simple MongoDB Query in php

That calculates total online in the past hour everything works fine

But i feel this way is not good for performance

Be cause query it's self return all matches data ( so there is unneeded data in that query )

What i needs is only the count of records

I have a collection that has millions of documents

Script:

<?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());
?>

Is my feeling rights ?


回答1:


I've found a much better solution MongoDB Command

Here is it

<?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);
?>


来源:https://stackoverflow.com/questions/42702331/php-mongodb-count-records

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!