Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP MongoDB Count Records

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 ?

like image 828
Ali Khazaee Avatar asked Mar 09 '17 17:03

Ali Khazaee


1 Answers

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);
?>
like image 143
Ali Khazaee Avatar answered Oct 19 '22 15:10

Ali Khazaee