简体   繁体   中英

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 ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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